FlatCAMApp.py 241 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945
  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 os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. import tkinter as tk
  19. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  20. import time # Just used for debugging. Double check before removing.
  21. import urllib.request, urllib.parse, urllib.error
  22. import webbrowser
  23. from contextlib import contextmanager
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from copy import copy,deepcopy
  26. import numpy as np
  27. from datetime import datetime
  28. import gc
  29. ########################################
  30. ## Imports part of FlatCAM ##
  31. ########################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from PlotCanvas import *
  35. from FlatCAMGUI import *
  36. from FlatCAMCommon import LoudDict
  37. from FlatCAMPostProc import load_postprocessors
  38. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  39. from FlatCAMProcess import *
  40. from FlatCAMWorkerStack import WorkerStack
  41. from VisPyVisuals import Color
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. from flatcamTools import *
  45. from multiprocessing import Pool
  46. import tclCommands
  47. from ParseFont import *
  48. ########################################
  49. ## App ##
  50. ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = '8.6 Beta1'
  80. version_date = "2019/01/06"
  81. # URL for update checks and statistics
  82. version_url = "http://flatcam.org/version"
  83. # App URL
  84. app_url = "http://flatcam.org"
  85. # Manual URL
  86. manual_url = "http://flatcam.org/manual/index.html"
  87. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  88. ##################
  89. ## Signals ##
  90. ##################
  91. # Inform the user
  92. # Handled by:
  93. # * App.info() --> Print on the status bar
  94. inform = QtCore.pyqtSignal(str)
  95. # General purpose background task
  96. worker_task = QtCore.pyqtSignal(dict)
  97. # File opened
  98. # Handled by:
  99. # * register_folder()
  100. # * register_recent()
  101. # Note: Setting the parameters to unicode does not seem
  102. # to have an effect. Then are received as Qstring
  103. # anyway.
  104. # File type and filename
  105. file_opened = QtCore.pyqtSignal(str, str)
  106. # File type and filename
  107. file_saved = QtCore.pyqtSignal(str, str)
  108. # Percentage of progress
  109. progress = QtCore.pyqtSignal(int)
  110. plots_updated = QtCore.pyqtSignal()
  111. # Emitted by new_object() and passes the new object as argument, plot flag.
  112. # on_object_created() adds the object to the collection, plots on appropriate flag
  113. # and emits new_object_available.
  114. object_created = QtCore.pyqtSignal(object, bool, bool)
  115. # Emitted when a object has been changed (like scaled, mirrored)
  116. object_changed = QtCore.pyqtSignal(object)
  117. # Emitted after object has been plotted.
  118. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  119. object_plotted = QtCore.pyqtSignal(object)
  120. # Emitted when a new object has been added to the collection
  121. # and is ready to be used.
  122. new_object_available = QtCore.pyqtSignal(object)
  123. message = QtCore.pyqtSignal(str, str, str)
  124. # Emmited when shell command is finished(one command only)
  125. shell_command_finished = QtCore.pyqtSignal(object)
  126. # Emitted when multiprocess pool has been recreated
  127. pool_recreated = QtCore.pyqtSignal(object)
  128. # Emitted when an unhandled exception happens
  129. # in the worker task.
  130. thread_exception = QtCore.pyqtSignal(object)
  131. def __init__(self, user_defaults=True, post_gui=None):
  132. """
  133. Starts the application.
  134. :return: app
  135. :rtype: App
  136. """
  137. App.log.info("FlatCAM Starting...")
  138. ###################
  139. ### OS-specific ###
  140. ###################
  141. # Folder for user settings.
  142. if sys.platform == 'win32':
  143. from win32com.shell import shell, shellcon
  144. if platform.architecture()[0] == '32bit':
  145. App.log.debug("Win32!")
  146. else:
  147. App.log.debug("Win64!")
  148. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  149. '/FlatCAM'
  150. self.os = 'windows'
  151. else: # Linux/Unix/MacOS
  152. self.data_path = os.path.expanduser('~') + \
  153. '/.FlatCAM'
  154. self.os = 'unix'
  155. ###############################
  156. ### Setup folders and files ###
  157. ###############################
  158. if not os.path.exists(self.data_path):
  159. os.makedirs(self.data_path)
  160. App.log.debug('Created data folder: ' + self.data_path)
  161. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  162. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  163. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  164. if not os.path.exists(self.postprocessorpaths):
  165. os.makedirs(self.postprocessorpaths)
  166. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  167. # create defaults.json file if there is none
  168. try:
  169. f = open(self.data_path + '/defaults.json')
  170. f.close()
  171. except IOError:
  172. App.log.debug('Creating empty defaults.json')
  173. f = open(self.data_path + '/defaults.json', 'w')
  174. json.dump({}, f)
  175. f.close()
  176. # create factory_defaults.json file if there is none
  177. try:
  178. f = open(self.data_path + '/factory_defaults.json')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty factory_defaults.json')
  182. f = open(self.data_path + '/factory_defaults.json', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. try:
  186. f = open(self.data_path + '/recent.json')
  187. f.close()
  188. except IOError:
  189. App.log.debug('Creating empty recent.json')
  190. f = open(self.data_path + '/recent.json', 'w')
  191. json.dump([], f)
  192. f.close()
  193. # Application directory. CHDIR to it. Otherwise, trying to load
  194. # GUI icons will fail as their path is relative.
  195. # This will fail under cx_freeze ...
  196. self.app_home = os.path.dirname(os.path.realpath(__file__))
  197. App.log.debug("Application path is " + self.app_home)
  198. App.log.debug("Started in " + os.getcwd())
  199. # cx_freeze workaround
  200. if os.path.isfile(self.app_home):
  201. self.app_home = os.path.dirname(self.app_home)
  202. os.chdir(self.app_home)
  203. # Create multiprocessing pool
  204. self.pool = Pool()
  205. ####################
  206. ## Initialize GUI ##
  207. ####################
  208. # FlatCAM colors used in plotting
  209. self.FC_light_green = '#BBF268BF'
  210. self.FC_dark_green = '#006E20BF'
  211. self.FC_light_blue = '#a5a5ffbf'
  212. self.FC_dark_blue = '#0000ffbf'
  213. QtCore.QObject.__init__(self)
  214. self.ui = FlatCAMGUI(self.version, self)
  215. # self.connect(self.ui,
  216. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  217. # self.save_geometry) PyQt4
  218. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  219. self.ui.final_save.connect(self.final_save)
  220. ##############
  221. #### Data ####
  222. ##############
  223. self.recent = []
  224. self.clipboard = QtWidgets.QApplication.clipboard()
  225. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  226. self.project_filename = None
  227. self.toggle_units_ignore = False
  228. # self.defaults_form = PreferencesUI()
  229. self.general_defaults_form = GeneralPreferencesUI()
  230. self.gerber_defaults_form = GerberPreferencesUI()
  231. self.excellon_defaults_form = ExcellonPreferencesUI()
  232. self.geometry_defaults_form = GeometryPreferencesUI()
  233. self.cncjob_defaults_form = CNCJobPreferencesUI()
  234. # when adding entries here read the comments in the method found bellow named:
  235. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  236. self.defaults_form_fields = {
  237. "units": self.general_defaults_form.general_group.units_radio,
  238. "global_shell_at_startup": self.general_defaults_form.general_group.shell_startup_cb,
  239. "global_gridx": self.general_defaults_form.general_group.gridx_entry,
  240. "global_gridy": self.general_defaults_form.general_group.gridy_entry,
  241. "global_plot_fill": self.general_defaults_form.general_group.pf_color_entry,
  242. "global_plot_line": self.general_defaults_form.general_group.pl_color_entry,
  243. "global_sel_fill": self.general_defaults_form.general_group.sf_color_entry,
  244. "global_sel_line": self.general_defaults_form.general_group.sl_color_entry,
  245. "global_alt_sel_fill": self.general_defaults_form.general_group.alt_sf_color_entry,
  246. "global_alt_sel_line": self.general_defaults_form.general_group.alt_sl_color_entry,
  247. "global_draw_color": self.general_defaults_form.general_group.draw_color_entry,
  248. "global_sel_draw_color": self.general_defaults_form.general_group.sel_draw_color_entry,
  249. "global_pan_button": self.general_defaults_form.general_group.pan_button_radio,
  250. "global_mselect_key": self.general_defaults_form.general_group.mselect_radio,
  251. # "global_pan_with_space_key": self.general_defaults_form.general_group.pan_with_space_cb,
  252. "global_workspace": self.general_defaults_form.general_group.workspace_cb,
  253. "global_workspaceT": self.general_defaults_form.general_group.wk_cb,
  254. "gerber_plot": self.gerber_defaults_form.gerber_group.plot_cb,
  255. "gerber_solid": self.gerber_defaults_form.gerber_group.solid_cb,
  256. "gerber_multicolored": self.gerber_defaults_form.gerber_group.multicolored_cb,
  257. "gerber_isotooldia": self.gerber_defaults_form.gerber_group.iso_tool_dia_entry,
  258. "gerber_isopasses": self.gerber_defaults_form.gerber_group.iso_width_entry,
  259. "gerber_isooverlap": self.gerber_defaults_form.gerber_group.iso_overlap_entry,
  260. "gerber_ncctools": self.gerber_defaults_form.gerber_group.ncc_tool_dia_entry,
  261. "gerber_nccoverlap": self.gerber_defaults_form.gerber_group.ncc_overlap_entry,
  262. "gerber_nccmargin": self.gerber_defaults_form.gerber_group.ncc_margin_entry,
  263. "gerber_nccmethod": self.gerber_defaults_form.gerber_group.ncc_method_radio,
  264. "gerber_nccconnect": self.gerber_defaults_form.gerber_group.ncc_connect_cb,
  265. "gerber_ncccontour": self.gerber_defaults_form.gerber_group.ncc_contour_cb,
  266. "gerber_nccrest": self.gerber_defaults_form.gerber_group.ncc_rest_cb,
  267. "gerber_combine_passes": self.gerber_defaults_form.gerber_group.combine_passes_cb,
  268. "gerber_milling_type": self.gerber_defaults_form.gerber_group.milling_type_radio,
  269. "gerber_cutouttooldia": self.gerber_defaults_form.gerber_group.cutout_tooldia_entry,
  270. "gerber_cutoutmargin": self.gerber_defaults_form.gerber_group.cutout_margin_entry,
  271. "gerber_cutoutgapsize": self.gerber_defaults_form.gerber_group.cutout_gap_entry,
  272. "gerber_gaps": self.gerber_defaults_form.gerber_group.gaps_radio,
  273. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_group.noncopper_margin_entry,
  274. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_group.noncopper_rounded_cb,
  275. "gerber_bboxmargin": self.gerber_defaults_form.gerber_group.bbmargin_entry,
  276. "gerber_bboxrounded": self.gerber_defaults_form.gerber_group.bbrounded_cb,
  277. "gerber_circle_steps": self.gerber_defaults_form.gerber_group.circle_steps_entry,
  278. "excellon_plot": self.excellon_defaults_form.excellon_group.plot_cb,
  279. "excellon_solid": self.excellon_defaults_form.excellon_group.solid_cb,
  280. "excellon_drillz": self.excellon_defaults_form.excellon_group.cutz_entry,
  281. "excellon_travelz": self.excellon_defaults_form.excellon_group.travelz_entry,
  282. "excellon_feedrate": self.excellon_defaults_form.excellon_group.feedrate_entry,
  283. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_group.feedrate_rapid_entry,
  284. "excellon_spindlespeed": self.excellon_defaults_form.excellon_group.spindlespeed_entry,
  285. "excellon_dwell": self.excellon_defaults_form.excellon_group.dwell_cb,
  286. "excellon_dwelltime": self.excellon_defaults_form.excellon_group.dwelltime_entry,
  287. "excellon_toolchange": self.excellon_defaults_form.excellon_group.toolchange_cb,
  288. "excellon_toolchangez": self.excellon_defaults_form.excellon_group.toolchangez_entry,
  289. "excellon_toolchangexy": self.excellon_defaults_form.excellon_group.toolchangexy_entry,
  290. "excellon_ppname_e": self.excellon_defaults_form.excellon_group.pp_excellon_name_cb,
  291. "excellon_startz": self.excellon_defaults_form.excellon_group.estartz_entry,
  292. "excellon_endz": self.excellon_defaults_form.excellon_group.eendz_entry,
  293. "excellon_tooldia": self.excellon_defaults_form.excellon_group.tooldia_entry,
  294. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_group.slot_tooldia_entry,
  295. "excellon_format_upper_in": self.excellon_defaults_form.excellon_group.excellon_format_upper_in_entry,
  296. "excellon_format_lower_in": self.excellon_defaults_form.excellon_group.excellon_format_lower_in_entry,
  297. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_group.excellon_format_upper_mm_entry,
  298. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_group.excellon_format_lower_mm_entry,
  299. "excellon_zeros": self.excellon_defaults_form.excellon_group.excellon_zeros_radio,
  300. "excellon_units": self.excellon_defaults_form.excellon_group.excellon_units_radio,
  301. "excellon_optimization_type": self.excellon_defaults_form.excellon_group.excellon_optimization_radio,
  302. "excellon_gcode_type": self.excellon_defaults_form.excellon_group.excellon_gcode_type_radio,
  303. "geometry_plot": self.geometry_defaults_form.geometry_group.plot_cb,
  304. "geometry_cutz": self.geometry_defaults_form.geometry_group.cutz_entry,
  305. "geometry_travelz": self.geometry_defaults_form.geometry_group.travelz_entry,
  306. "geometry_feedrate": self.geometry_defaults_form.geometry_group.cncfeedrate_entry,
  307. "geometry_feedrate_z": self.geometry_defaults_form.geometry_group.cncplunge_entry,
  308. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_group.cncfeedrate_rapid_entry,
  309. "geometry_cnctooldia": self.geometry_defaults_form.geometry_group.cnctooldia_entry,
  310. "geometry_painttooldia": self.geometry_defaults_form.geometry_group.painttooldia_entry,
  311. "geometry_spindlespeed": self.geometry_defaults_form.geometry_group.cncspindlespeed_entry,
  312. "geometry_dwell": self.geometry_defaults_form.geometry_group.dwell_cb,
  313. "geometry_dwelltime": self.geometry_defaults_form.geometry_group.dwelltime_entry,
  314. "geometry_paintoverlap": self.geometry_defaults_form.geometry_group.paintoverlap_entry,
  315. "geometry_paintmargin": self.geometry_defaults_form.geometry_group.paintmargin_entry,
  316. "geometry_paintmethod": self.geometry_defaults_form.geometry_group.paintmethod_combo,
  317. "geometry_selectmethod": self.geometry_defaults_form.geometry_group.selectmethod_combo,
  318. "geometry_pathconnect": self.geometry_defaults_form.geometry_group.pathconnect_cb,
  319. "geometry_paintcontour": self.geometry_defaults_form.geometry_group.contour_cb,
  320. "geometry_ppname_g": self.geometry_defaults_form.geometry_group.pp_geometry_name_cb,
  321. "geometry_toolchange": self.geometry_defaults_form.geometry_group.toolchange_cb,
  322. "geometry_toolchangez": self.geometry_defaults_form.geometry_group.toolchangez_entry,
  323. "geometry_toolchangexy": self.geometry_defaults_form.geometry_group.toolchangexy_entry,
  324. "geometry_startz": self.geometry_defaults_form.geometry_group.gstartz_entry,
  325. "geometry_endz": self.geometry_defaults_form.geometry_group.gendz_entry,
  326. "geometry_multidepth": self.geometry_defaults_form.geometry_group.multidepth_cb,
  327. "geometry_depthperpass": self.geometry_defaults_form.geometry_group.depthperpass_entry,
  328. "geometry_extracut": self.geometry_defaults_form.geometry_group.extracut_cb,
  329. "geometry_circle_steps": self.geometry_defaults_form.geometry_group.circle_steps_entry,
  330. "cncjob_plot": self.cncjob_defaults_form.cncjob_group.plot_cb,
  331. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_group.tooldia_entry,
  332. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_group.coords_dec_entry,
  333. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_group.fr_dec_entry,
  334. "cncjob_prepend": self.cncjob_defaults_form.cncjob_group.prepend_text,
  335. "cncjob_append": self.cncjob_defaults_form.cncjob_group.append_text,
  336. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_group.steps_per_circle_entry
  337. }
  338. # loads postprocessors
  339. self.postprocessors = load_postprocessors(self)
  340. for name in list(self.postprocessors.keys()):
  341. self.geometry_defaults_form.geometry_group.pp_geometry_name_cb.addItem(name)
  342. self.excellon_defaults_form.excellon_group.pp_excellon_name_cb.addItem(name)
  343. self.defaults = LoudDict()
  344. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  345. self.defaults.update({
  346. "global_serial": 0,
  347. "global_stats": {},
  348. "units": "IN",
  349. "global_gridx": 1.0,
  350. "global_gridy": 1.0,
  351. "global_plot_fill": '#BBF268BF',
  352. "global_plot_line": '#006E20BF',
  353. "global_sel_fill": '#a5a5ffbf',
  354. "global_sel_line": '#0000ffbf',
  355. "global_alt_sel_fill": '#BBF268BF',
  356. "global_alt_sel_line": '#006E20BF',
  357. "global_draw_color": '#FF0000',
  358. "global_sel_draw_color": '#0000FF',
  359. "global_pan_button": '2',
  360. "global_mselect_key": 'Control',
  361. # "global_pan_with_space_key": False,
  362. "global_workspace": False,
  363. "global_workspaceT": "A4P",
  364. "global_toolbar_view": 31,
  365. "gerber_plot": True,
  366. "gerber_solid": True,
  367. "gerber_multicolored": False,
  368. "gerber_isotooldia": 0.016,
  369. "gerber_isopasses": 1,
  370. "gerber_isooverlap": 0.15,
  371. "gerber_ncctools": "1.0, 0.5",
  372. "gerber_nccoverlap": 0.4,
  373. "gerber_nccmargin": 1,
  374. "gerber_nccmethod": "seed",
  375. "gerber_nccconnect": True,
  376. "gerber_ncccontour": True,
  377. "gerber_nccrest": False,
  378. "gerber_combine_passes": False,
  379. "gerber_milling_type": "cl",
  380. "gerber_cutouttooldia": 0.07,
  381. "gerber_cutoutmargin": 0.1,
  382. "gerber_cutoutgapsize": 0.15,
  383. "gerber_gaps": "4",
  384. "gerber_noncoppermargin": 0.0,
  385. "gerber_noncopperrounded": False,
  386. "gerber_bboxmargin": 0.0,
  387. "gerber_bboxrounded": False,
  388. "gerber_circle_steps": 64,
  389. "excellon_plot": True,
  390. "excellon_solid": False,
  391. "excellon_drillz": -0.1,
  392. "excellon_travelz": 0.1,
  393. "excellon_feedrate": 3.0,
  394. "excellon_feedrate_rapid": 3.0,
  395. "excellon_spindlespeed": None,
  396. "excellon_dwell": False,
  397. "excellon_dwelltime": 1,
  398. "excellon_toolchange": False,
  399. "excellon_toolchangez": 1.0,
  400. "excellon_toolchangexy": "0.0, 0.0",
  401. "excellon_tooldia": 0.016,
  402. "excellon_slot_tooldia": 0.016,
  403. "excellon_startz": None,
  404. "excellon_endz": 2.0,
  405. "excellon_ppname_e": 'default',
  406. "excellon_format_upper_in": 2,
  407. "excellon_format_lower_in": 4,
  408. "excellon_format_upper_mm": 3,
  409. "excellon_format_lower_mm": 3,
  410. "excellon_zeros": "L",
  411. "excellon_units": "INCH",
  412. "excellon_optimization_type": 'B',
  413. "excellon_search_time": 3,
  414. "excellon_gcode_type": "drills",
  415. "geometry_plot": True,
  416. "geometry_cutz": -0.002,
  417. "geometry_travelz": 0.1,
  418. "geometry_toolchange": False,
  419. "geometry_toolchangez": 1.0,
  420. "geometry_toolchangexy": "0.0, 0.0",
  421. "geometry_startz": None,
  422. "geometry_endz": 2.0,
  423. "geometry_feedrate": 3.0,
  424. "geometry_feedrate_z": 3.0,
  425. "geometry_feedrate_rapid": 3.0,
  426. "geometry_cnctooldia": 0.016,
  427. "geometry_spindlespeed": None,
  428. "geometry_dwell": False,
  429. "geometry_dwelltime": 1,
  430. "geometry_painttooldia": 0.07,
  431. "geometry_paintoverlap": 0.15,
  432. "geometry_paintmargin": 0.0,
  433. "geometry_paintmethod": "seed",
  434. "geometry_selectmethod": "single",
  435. "geometry_pathconnect": True,
  436. "geometry_paintcontour": True,
  437. "geometry_ppname_g": 'default',
  438. "geometry_depthperpass": 0.002,
  439. "geometry_multidepth": False,
  440. "geometry_extracut": False,
  441. "geometry_circle_steps": 64,
  442. "cncjob_plot": True,
  443. "cncjob_tooldia": 0.0393701,
  444. "cncjob_coords_decimals": 4,
  445. "cncjob_fr_decimals": 2,
  446. "cncjob_prepend": "",
  447. "cncjob_append": "",
  448. "cncjob_steps_per_circle": 64,
  449. "global_background_timeout": 300000, # Default value is 5 minutes
  450. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  451. # (python trace only for unknown errors),
  452. # 1 = show trace(show trace allways),
  453. # 2 = (For the future).
  454. # Persistence
  455. "global_last_folder": None,
  456. "global_last_save_folder": None,
  457. # Default window geometry
  458. "global_def_win_x": 100,
  459. "global_def_win_y": 100,
  460. "global_def_win_w": 1024,
  461. "global_def_win_h": 650,
  462. # Constants...
  463. "global_defaults_save_period_ms": 20000, # Time between default saves.
  464. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  465. "global_shell_at_startup": False, # Show the shell at startup.
  466. "global_recent_limit": 10, # Max. items in recent list.
  467. "fit_key": '1',
  468. "zoom_out_key": '2',
  469. "zoom_in_key": '3',
  470. "grid_toggle_key": 'G',
  471. "zoom_ratio": 1.5,
  472. "global_point_clipboard_format": "(%.4f, %.4f)",
  473. "global_zdownrate": None,
  474. "gerber_use_buffer_for_union": True
  475. })
  476. ###############################
  477. ### Load defaults from file ###
  478. if user_defaults:
  479. self.load_defaults()
  480. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  481. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  482. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  483. self.save_defaults(silent=True)
  484. self.propagate_defaults(silent=True)
  485. self.restore_main_win_geom()
  486. def auto_save_defaults():
  487. try:
  488. self.save_defaults(silent=True)
  489. self.propagate_defaults(silent=True)
  490. finally:
  491. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  492. # the following lines activates automatic defaults save
  493. # if user_defaults:
  494. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  495. # self.options_form = PreferencesUI()
  496. self.general_options_form = GeneralPreferencesUI()
  497. self.gerber_options_form = GerberPreferencesUI()
  498. self.excellon_options_form = ExcellonPreferencesUI()
  499. self.geometry_options_form = GeometryPreferencesUI()
  500. self.cncjob_options_form = CNCJobPreferencesUI()
  501. self.options_form_fields = {
  502. "units": self.general_options_form.general_group.units_radio,
  503. "global_gridx": self.general_options_form.general_group.gridx_entry,
  504. "global_gridy": self.general_options_form.general_group.gridy_entry,
  505. "gerber_plot": self.gerber_options_form.gerber_group.plot_cb,
  506. "gerber_solid": self.gerber_options_form.gerber_group.solid_cb,
  507. "gerber_multicolored": self.gerber_options_form.gerber_group.multicolored_cb,
  508. "gerber_isotooldia": self.gerber_options_form.gerber_group.iso_tool_dia_entry,
  509. "gerber_isopasses": self.gerber_options_form.gerber_group.iso_width_entry,
  510. "gerber_isooverlap": self.gerber_options_form.gerber_group.iso_overlap_entry,
  511. "gerber_ncctools": self.gerber_options_form.gerber_group.ncc_tool_dia_entry,
  512. "gerber_nccoverlap": self.gerber_options_form.gerber_group.ncc_overlap_entry,
  513. "gerber_nccmargin": self.gerber_options_form.gerber_group.ncc_margin_entry,
  514. "gerber_combine_passes": self.gerber_options_form.gerber_group.combine_passes_cb,
  515. "gerber_cutouttooldia": self.gerber_options_form.gerber_group.cutout_tooldia_entry,
  516. "gerber_cutoutmargin": self.gerber_options_form.gerber_group.cutout_margin_entry,
  517. "gerber_cutoutgapsize": self.gerber_options_form.gerber_group.cutout_gap_entry,
  518. "gerber_gaps": self.gerber_options_form.gerber_group.gaps_radio,
  519. "gerber_noncoppermargin": self.gerber_options_form.gerber_group.noncopper_margin_entry,
  520. "gerber_noncopperrounded": self.gerber_options_form.gerber_group.noncopper_rounded_cb,
  521. "gerber_bboxmargin": self.gerber_options_form.gerber_group.bbmargin_entry,
  522. "gerber_bboxrounded": self.gerber_options_form.gerber_group.bbrounded_cb,
  523. "excellon_plot": self.excellon_options_form.excellon_group.plot_cb,
  524. "excellon_solid": self.excellon_options_form.excellon_group.solid_cb,
  525. "excellon_drillz": self.excellon_options_form.excellon_group.cutz_entry,
  526. "excellon_travelz": self.excellon_options_form.excellon_group.travelz_entry,
  527. "excellon_feedrate": self.excellon_options_form.excellon_group.feedrate_entry,
  528. "excellon_feedrate_rapid": self.excellon_options_form.excellon_group.feedrate_rapid_entry,
  529. "excellon_spindlespeed": self.excellon_options_form.excellon_group.spindlespeed_entry,
  530. "excellon_dwell": self.excellon_options_form.excellon_group.dwell_cb,
  531. "excellon_dwelltime": self.excellon_options_form.excellon_group.dwelltime_entry,
  532. "excellon_toolchange": self.excellon_options_form.excellon_group.toolchange_cb,
  533. "excellon_toolchangez": self.excellon_options_form.excellon_group.toolchangez_entry,
  534. "excellon_toolchangexy": self.excellon_options_form.excellon_group.toolchangexy_entry,
  535. "excellon_tooldia": self.excellon_options_form.excellon_group.tooldia_entry,
  536. "excellon_ppname_e": self.excellon_options_form.excellon_group.pp_excellon_name_cb,
  537. "excellon_startz": self.excellon_options_form.excellon_group.estartz_entry,
  538. "excellon_endz": self.excellon_options_form.excellon_group.eendz_entry,
  539. "excellon_format_upper_in": self.excellon_options_form.excellon_group.excellon_format_upper_in_entry,
  540. "excellon_format_lower_in": self.excellon_options_form.excellon_group.excellon_format_lower_in_entry,
  541. "excellon_format_upper_mm": self.excellon_options_form.excellon_group.excellon_format_upper_mm_entry,
  542. "excellon_format_lower_mm": self.excellon_options_form.excellon_group.excellon_format_lower_mm_entry,
  543. "excellon_zeros": self.excellon_options_form.excellon_group.excellon_zeros_radio,
  544. "excellon_units": self.excellon_options_form.excellon_group.excellon_units_radio,
  545. "excellon_optimization_type": self.excellon_options_form.excellon_group.excellon_optimization_radio,
  546. "geometry_plot": self.geometry_options_form.geometry_group.plot_cb,
  547. "geometry_cutz": self.geometry_options_form.geometry_group.cutz_entry,
  548. "geometry_travelz": self.geometry_options_form.geometry_group.travelz_entry,
  549. "geometry_feedrate": self.geometry_options_form.geometry_group.cncfeedrate_entry,
  550. "geometry_feedrate_z": self.geometry_options_form.geometry_group.cncplunge_entry,
  551. "geometry_feedrate_rapid": self.geometry_options_form.geometry_group.cncfeedrate_rapid_entry,
  552. "geometry_spindlespeed": self.geometry_options_form.geometry_group.cncspindlespeed_entry,
  553. "geometry_dwell": self.geometry_options_form.geometry_group.dwell_cb,
  554. "geometry_dwelltime": self.geometry_options_form.geometry_group.dwelltime_entry,
  555. "geometry_cnctooldia": self.geometry_options_form.geometry_group.cnctooldia_entry,
  556. "geometry_painttooldia": self.geometry_options_form.geometry_group.painttooldia_entry,
  557. "geometry_paintoverlap": self.geometry_options_form.geometry_group.paintoverlap_entry,
  558. "geometry_paintmargin": self.geometry_options_form.geometry_group.paintmargin_entry,
  559. "geometry_selectmethod": self.geometry_options_form.geometry_group.selectmethod_combo,
  560. "geometry_ppname_g": self.geometry_options_form.geometry_group.pp_geometry_name_cb,
  561. "geometry_toolchange": self.geometry_options_form.geometry_group.toolchange_cb,
  562. "geometry_toolchangez": self.geometry_options_form.geometry_group.toolchangez_entry,
  563. "geometry_toolchangexy": self.geometry_options_form.geometry_group.toolchangexy_entry,
  564. "geometry_startz": self.geometry_options_form.geometry_group.gstartz_entry,
  565. "geometry_endz": self.geometry_options_form.geometry_group.gendz_entry,
  566. "geometry_depthperpass": self.geometry_options_form.geometry_group.depthperpass_entry,
  567. "geometry_multidepth": self.geometry_options_form.geometry_group.multidepth_cb,
  568. "geometry_extracut": self.geometry_options_form.geometry_group.extracut_cb,
  569. "cncjob_plot": self.cncjob_options_form.cncjob_group.plot_cb,
  570. "cncjob_tooldia": self.cncjob_options_form.cncjob_group.tooldia_entry,
  571. "cncjob_prepend": self.cncjob_options_form.cncjob_group.prepend_text,
  572. "cncjob_append": self.cncjob_options_form.cncjob_group.append_text
  573. }
  574. for name in list(self.postprocessors.keys()):
  575. self.geometry_options_form.geometry_group.pp_geometry_name_cb.addItem(name)
  576. self.excellon_options_form.excellon_group.pp_excellon_name_cb.addItem(name)
  577. self.options = LoudDict()
  578. self.options.set_change_callback(self.on_options_dict_change)
  579. self.options.update({
  580. "units": "IN",
  581. "global_gridx": 1.0,
  582. "global_gridy": 1.0,
  583. "gerber_plot": True,
  584. "gerber_solid": True,
  585. "gerber_multicolored": False,
  586. "gerber_isotooldia": 0.016,
  587. "gerber_isopasses": 1,
  588. "gerber_isooverlap": 0.15,
  589. "gerber_ncctools": "1.0, 0.5",
  590. "gerber_nccoverlap": 0.4,
  591. "gerber_nccmargin": 1,
  592. "gerber_combine_passes": True,
  593. "gerber_cutouttooldia": 0.07,
  594. "gerber_cutoutmargin": 0.1,
  595. "gerber_cutoutgapsize": 0.15,
  596. "gerber_gaps": "4",
  597. "gerber_noncoppermargin": 0.0,
  598. "gerber_noncopperrounded": False,
  599. "gerber_bboxmargin": 0.0,
  600. "gerber_bboxrounded": False,
  601. "excellon_plot": True,
  602. "excellon_solid": False,
  603. "excellon_drillz": -0.1,
  604. "excellon_travelz": 0.1,
  605. "excellon_feedrate": 3.0,
  606. "excellon_feedrate_rapid": 3.0,
  607. "excellon_spindlespeed": None,
  608. "excellon_dwell": True,
  609. "excellon_dwelltime": 1000,
  610. "excellon_toolchange": False,
  611. "excellon_toolchangez": 1.0,
  612. "excellon_toolchangexy": "0.0, 0.0",
  613. "excellon_tooldia": 0.016,
  614. "excellon_ppname_e": 'default',
  615. "excellon_format_upper_in": 2,
  616. "excellon_format_lower_in": 4,
  617. "excellon_format_upper_mm": 3,
  618. "excellon_format_lower_mm": 3,
  619. "excellon_units": 'INCH',
  620. "excellon_optimization_type": 'B',
  621. "excellon_search_time": 3,
  622. "excellon_startz": None,
  623. "excellon_endz": 2.0,
  624. "excellon_zeros": "L",
  625. "geometry_plot": True,
  626. "geometry_cutz": -0.002,
  627. "geometry_travelz": 0.1,
  628. "geometry_feedrate": 3.0,
  629. "geometry_feedrate_z": 3.0,
  630. "geometry_feedrate_rapid": 3.0,
  631. "geometry_spindlespeed": None,
  632. "geometry_dwell": True,
  633. "geometry_dwelltime": 1000,
  634. "geometry_cnctooldia": 0.016,
  635. "geometry_painttooldia": 0.07,
  636. "geometry_paintoverlap": 0.15,
  637. "geometry_paintmargin": 0.0,
  638. "geometry_selectmethod": "single",
  639. "geometry_toolchange": False,
  640. "geometry_toolchangez": 2.0,
  641. "geometry_toolchangexy": "0.0, 0.0",
  642. "geometry_startz": None,
  643. "geometry_endz": 2.0,
  644. "geometry_ppname_g": "default",
  645. "geometry_depthperpass": 0.002,
  646. "geometry_multidepth": False,
  647. "geometry_extracut": False,
  648. "cncjob_plot": True,
  649. "cncjob_tooldia": 0.016,
  650. "cncjob_prepend": "",
  651. "cncjob_append": "",
  652. "global_background_timeout": 300000, # Default value is 5 minutes
  653. "global_verbose_error_level": 0, # Shell verbosity:
  654. # 0 = default(python trace only for unknown errors),
  655. # 1 = show trace(show trace allways), 2 = (For the future).
  656. })
  657. self.options.update(self.defaults) # Copy app defaults to project options
  658. self.gen_form = None
  659. self.ger_form = None
  660. self.exc_form = None
  661. self.geo_form = None
  662. self.cnc_form = None
  663. self.on_options_combo_change(0) # Will show the initial form
  664. ### Define OBJECT COLLECTION ###
  665. self.collection = ObjectCollection(self)
  666. self.ui.project_tab_layout.addWidget(self.collection.view)
  667. ###
  668. self.log.debug("Finished creating Object Collection.")
  669. ### Initialize the color box's color in Preferences -> Global -> Color
  670. # Init Plot Colors
  671. self.general_defaults_form.general_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  672. self.general_defaults_form.general_group.pf_color_button.setStyleSheet(
  673. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  674. self.general_defaults_form.general_group.pf_color_alpha_spinner.set_value(
  675. int(self.defaults['global_plot_fill'][7:9], 16))
  676. self.general_defaults_form.general_group.pf_color_alpha_slider.setValue(
  677. int(self.defaults['global_plot_fill'][7:9], 16))
  678. self.general_defaults_form.general_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  679. self.general_defaults_form.general_group.pl_color_button.setStyleSheet(
  680. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  681. # Init Left-Right Selection colors
  682. self.general_defaults_form.general_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  683. self.general_defaults_form.general_group.sf_color_button.setStyleSheet(
  684. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  685. self.general_defaults_form.general_group.sf_color_alpha_spinner.set_value(
  686. int(self.defaults['global_sel_fill'][7:9], 16))
  687. self.general_defaults_form.general_group.sf_color_alpha_slider.setValue(
  688. int(self.defaults['global_sel_fill'][7:9], 16))
  689. self.general_defaults_form.general_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  690. self.general_defaults_form.general_group.sl_color_button.setStyleSheet(
  691. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  692. # Init Right-Left Selection colors
  693. self.general_defaults_form.general_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  694. self.general_defaults_form.general_group.alt_sf_color_button.setStyleSheet(
  695. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  696. self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.set_value(
  697. int(self.defaults['global_sel_fill'][7:9], 16))
  698. self.general_defaults_form.general_group.alt_sf_color_alpha_slider.setValue(
  699. int(self.defaults['global_sel_fill'][7:9], 16))
  700. self.general_defaults_form.general_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  701. self.general_defaults_form.general_group.alt_sl_color_button.setStyleSheet(
  702. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  703. # Init Draw color and Selection Draw Color
  704. self.general_defaults_form.general_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  705. self.general_defaults_form.general_group.draw_color_button.setStyleSheet(
  706. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  707. self.general_defaults_form.general_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  708. self.general_defaults_form.general_group.sel_draw_color_button.setStyleSheet(
  709. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  710. #### End of Data ####
  711. #### Plot Area ####
  712. start_plot_time = time.time() # debug
  713. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  714. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  715. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  716. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  717. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  718. # Keys over plot enabled
  719. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  720. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  721. self.ui.splitter.setStretchFactor(1, 2)
  722. # So it can receive key presses
  723. self.plotcanvas.vispy_canvas.native.setFocus()
  724. self.app_cursor = self.plotcanvas.new_cursor()
  725. self.app_cursor.enabled = False
  726. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  727. # depending on from where those tools are called different actions can be done
  728. self.call_source = 'app'
  729. end_plot_time = time.time()
  730. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  731. ### EDITOR section
  732. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  733. self.exc_editor = FlatCAMExcEditor(self)
  734. # start with GRID activated
  735. self.ui.grid_snap_btn.trigger()
  736. self.ui.corner_snap_btn.setEnabled(False)
  737. self.ui.snap_max_dist_entry.setEnabled(False)
  738. self.ui.g_editor_cmenu.setEnabled(False)
  739. self.ui.e_editor_cmenu.setEnabled(False)
  740. #### Adjust tabs width ####
  741. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  742. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  743. self.collection.view.setMinimumWidth(290)
  744. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  745. #### Worker ####
  746. self.workers = WorkerStack()
  747. self.worker_task.connect(self.workers.add_task)
  748. ### Signal handling ###
  749. ## Custom signals
  750. self.inform.connect(self.info)
  751. self.message.connect(self.message_dialog)
  752. self.progress.connect(self.set_progress_bar)
  753. self.object_created.connect(self.on_object_created)
  754. self.object_changed.connect(self.on_object_changed)
  755. self.object_plotted.connect(self.on_object_plotted)
  756. self.plots_updated.connect(self.on_plots_updated)
  757. self.file_opened.connect(self.register_recent)
  758. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  759. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  760. ## Standard signals
  761. # Menu
  762. self.ui.menufilenew.triggered.connect(self.on_file_new)
  763. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  764. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  765. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  766. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  767. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  768. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  769. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  770. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  771. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  772. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  773. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  774. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  775. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  776. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  777. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  778. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  779. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  780. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  781. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  782. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  783. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  784. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  785. self.ui.menueditedit.triggered.connect(self.object2editor)
  786. self.ui.menueditok.triggered.connect(self.editor2object)
  787. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  788. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  789. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  790. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  791. self.ui.menueditdelete.triggered.connect(self.on_delete)
  792. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  793. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  794. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  795. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  796. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  797. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  798. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  799. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  800. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  801. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  802. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  803. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  804. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  805. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  806. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  807. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  808. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  809. self.ui.menuviewdisableall.triggered.connect(lambda: self.disable_plots(self.collection.get_list()))
  810. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(self.collection.get_non_selected()))
  811. self.ui.menuviewenable.triggered.connect(lambda: self.enable_plots(self.collection.get_list()))
  812. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  813. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  814. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  815. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  816. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  817. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  818. self.ui.menuhelp_about.triggered.connect(self.on_about)
  819. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  820. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  821. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  822. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  823. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  824. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  825. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  826. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  827. # Toolbar
  828. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  829. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  830. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  831. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  832. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  833. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  834. self.ui.replot_btn.triggered.connect(self.plot_all)
  835. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  836. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  837. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  838. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  839. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  840. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  841. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  842. self.ui.delete_btn.triggered.connect(self.on_delete)
  843. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  844. # Context Menu
  845. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  846. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  847. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  848. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  849. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  850. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  851. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  852. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  853. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  854. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  855. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  856. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  857. self.ui.clearplot.triggered.connect(self.clear_plots)
  858. self.ui.replot.triggered.connect(self.plot_all)
  859. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  860. # Preferences Plot Area TAB
  861. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  862. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  863. self.ui.pref_factory_button.clicked.connect(self.load_factory_defaults)
  864. self.ui.pref_load_button.clicked.connect(self.load_user_defaults)
  865. self.general_options_form.general_group.units_radio.group_toggle_fn = self.on_toggle_units
  866. # Setting plot colors signals
  867. self.general_defaults_form.general_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  868. self.general_defaults_form.general_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  869. self.general_defaults_form.general_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  870. self.general_defaults_form.general_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  871. self.general_defaults_form.general_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  872. self.general_defaults_form.general_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  873. # Setting selection (left - right) colors signals
  874. self.general_defaults_form.general_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  875. self.general_defaults_form.general_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  876. self.general_defaults_form.general_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  877. self.general_defaults_form.general_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  878. self.general_defaults_form.general_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  879. self.general_defaults_form.general_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  880. # Setting selection (right - left) colors signals
  881. self.general_defaults_form.general_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  882. self.general_defaults_form.general_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  883. self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  884. self.on_alt_sf_color_spinner)
  885. self.general_defaults_form.general_group.alt_sf_color_alpha_slider.valueChanged.connect(
  886. self.on_alt_sf_color_slider)
  887. self.general_defaults_form.general_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  888. self.general_defaults_form.general_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  889. # Setting Editor Draw colors signals
  890. self.general_defaults_form.general_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  891. self.general_defaults_form.general_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  892. self.general_defaults_form.general_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  893. self.general_defaults_form.general_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  894. self.general_defaults_form.general_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  895. self.general_defaults_form.general_group.workspace_cb.stateChanged.connect(self.on_workspace)
  896. # Modify G-CODE Plot Area TAB
  897. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  898. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  899. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  900. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  901. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  902. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  903. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  904. # Object list
  905. self.collection.view.activated.connect(self.on_row_activated)
  906. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  907. self.general_defaults_form.general_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  908. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  909. self.excellon_defaults_form.excellon_group.excellon_defaults_button.clicked.connect(
  910. self.on_excellon_defaults_button)
  911. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  912. self.excellon_options_form.excellon_group.excellon_defaults_button.clicked.connect(
  913. self.on_excellon_options_button)
  914. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  915. self.tool_tab_locked = False
  916. ####################
  917. ### Other setups ###
  918. ####################
  919. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  920. self.setup_obj_classes()
  921. self.setup_recent_items()
  922. self.setup_component_editor()
  923. #############
  924. ### Shell ###
  925. #############
  926. ###
  927. # Auto-complete KEYWORDS
  928. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  929. 'aligndrill', 'clear',
  930. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob', 'export_gcode',
  931. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  932. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  933. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  934. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  935. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  936. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  937. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  938. ]
  939. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  940. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  941. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  942. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  943. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  944. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  945. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  946. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  947. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  948. ]
  949. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  950. self.shell = FCShell(self, version=self.version)
  951. self.shell._edit.set_model_data(self.myKeywords)
  952. self.shell.setWindowIcon(self.ui.app_icon)
  953. self.shell.setWindowTitle("FlatCAM Shell")
  954. self.shell.resize(*self.defaults["global_shell_shape"])
  955. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  956. self.shell.append_output("(Type help to get started)\n\n")
  957. self.init_tcl()
  958. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  959. self.ui.shell_dock.setWidget(self.shell)
  960. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  961. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  962. QtWidgets.QDockWidget.DockWidgetFloatable |
  963. QtWidgets.QDockWidget.DockWidgetClosable)
  964. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  965. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  966. if self.defaults["global_shell_at_startup"]:
  967. self.ui.shell_dock.show()
  968. else:
  969. self.ui.shell_dock.hide()
  970. #########################
  971. ### Tools and Plugins ###
  972. #########################
  973. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  974. self.install_tools()
  975. ### System Font Parsing ###
  976. self.f_parse = ParseFont()
  977. self.parse_system_fonts()
  978. # test if the program was started with a script as parameter
  979. if self.cmd_line_shellfile:
  980. try:
  981. with open(self.cmd_line_shellfile, "r") as myfile:
  982. cmd_line_shellfile_text = myfile.read()
  983. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  984. except Exception as ext:
  985. print("ERROR: ", ext)
  986. sys.exit(2)
  987. # coordinates for relative position display
  988. self.rel_point1 = (0, 0)
  989. self.rel_point2 = (0, 0)
  990. # variable to store coordinates
  991. self.pos = (0, 0)
  992. self.pos_jump = (0, 0)
  993. # variable to store if there was motion before right mouse button click (panning)
  994. self.panning_action = False
  995. # variable to store if a command is active (then the var is not None) and which one it is
  996. self.command_active = None
  997. # variable to store the status of moving selection action
  998. # None value means that it's not an selection action
  999. # True value = a selection from left to right
  1000. # False value = a selection from right to left
  1001. self.selection_type = None
  1002. # List to store the objects that are currently loaded in FlatCAM
  1003. # This list is updated on each object creation or object delete
  1004. self.all_objects_list = []
  1005. # List to store the objects that are selected
  1006. self.sel_objects_list = []
  1007. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1008. self.key_modifiers = None
  1009. # Variable to hold the status of the axis
  1010. self.toggle_axis = True
  1011. self.cursor = None
  1012. # Variable to store the GCODE that was edited
  1013. self.gcode_edited = ""
  1014. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1015. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1016. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1017. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1018. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1019. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1020. 'mpf']
  1021. self.svg_list = ['svg']
  1022. self.dxf_list = ['dxf']
  1023. self.prj_list = ['flatprj']
  1024. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1025. # flag for polygons not cleared
  1026. self.poly_not_cleared = False
  1027. ### Save defaults to factory_defaults.json file ###
  1028. ### It's done only once after install #############
  1029. factory_file = open(self.data_path + '/factory_defaults.json')
  1030. fac_def_from_file = factory_file.read()
  1031. factory_defaults = json.loads(fac_def_from_file)
  1032. # if the file contain an empty dictionary then save the factory defaults into the file
  1033. if not factory_defaults:
  1034. self.save_factory_defaults(silent=False)
  1035. factory_file.close()
  1036. # Post-GUI initialization: Experimental attempt
  1037. # to perform unit tests on the GUI.
  1038. # if post_gui is not None:
  1039. # post_gui(self)
  1040. App.log.debug("END of constructor. Releasing control.")
  1041. # accept a project file as command line parameter
  1042. # the path/file_name must be enclosed in quotes if it contain spaces
  1043. for argument in App.args:
  1044. if '.FlatPrj' in argument:
  1045. try:
  1046. project_name = str(argument)
  1047. if project_name == "":
  1048. self.inform.emit("Open cancelled.")
  1049. else:
  1050. # self.open_project(project_name)
  1051. run_from_arg = True
  1052. self.worker_task.emit({'fcn': self.open_project,
  1053. 'params': [project_name, run_from_arg]})
  1054. except Exception as e:
  1055. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1056. def defaults_read_form(self):
  1057. for option in self.defaults_form_fields:
  1058. try:
  1059. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1060. except:
  1061. pass
  1062. def defaults_write_form(self):
  1063. for option in self.defaults:
  1064. self.defaults_write_form_field(option)
  1065. # try:
  1066. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1067. # except KeyError:
  1068. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1069. # # TODO: Rethink this?
  1070. # pass
  1071. def defaults_write_form_field(self, field):
  1072. try:
  1073. self.defaults_form_fields[field].set_value(self.defaults[field])
  1074. except KeyError:
  1075. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1076. # TODO: Rethink this?
  1077. pass
  1078. def clear_pool(self):
  1079. self.pool.close()
  1080. self.pool = Pool()
  1081. self.pool_recreated.emit(self.pool)
  1082. gc.collect()
  1083. # the order that the tools are installed is important as they can depend on each other install position
  1084. def install_tools(self):
  1085. self.dblsidedtool = DblSidedTool(self)
  1086. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1087. self.measurement_tool = Measurement(self)
  1088. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1089. self.panelize_tool = Panelize(self)
  1090. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1091. self.film_tool = Film(self)
  1092. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1093. self.move_tool = ToolMove(self)
  1094. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1095. before=self.ui.menueditorigin)
  1096. self.cutout_tool = ToolCutout(self)
  1097. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1098. before=self.measurement_tool.menuAction)
  1099. self.ncclear_tool = NonCopperClear(self)
  1100. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1101. before=self.measurement_tool.menuAction, separator=True)
  1102. self.paint_tool = ToolPaint(self)
  1103. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1104. before=self.measurement_tool.menuAction, separator=True)
  1105. self.calculator_tool = ToolCalculator(self)
  1106. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1107. self.transform_tool = ToolTransform(self)
  1108. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1109. self.properties_tool = Properties(self)
  1110. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1111. self.image_tool = ToolImage(self)
  1112. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1113. separator=True)
  1114. self.log.debug("Tools are installed.")
  1115. def init_tools(self):
  1116. # delete the data currently in the Tools Tab and the Tab itself
  1117. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1118. if widget is not None:
  1119. widget.deleteLater()
  1120. self.ui.notebook.removeTab(2)
  1121. # rebuild the Tools Tab
  1122. self.ui.tool_tab = QtWidgets.QWidget()
  1123. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1124. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1125. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1126. self.ui.tool_scroll_area = VerticalScrollArea()
  1127. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1128. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1129. self.install_tools()
  1130. self.log.debug("Tools are initialized.")
  1131. def parse_system_fonts(self):
  1132. self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1133. 'params': []})
  1134. def object2editor(self):
  1135. """
  1136. Send the current Geometry or Excellon object (if any) into the editor.
  1137. :return: None
  1138. """
  1139. if isinstance(self.collection.get_active(), FlatCAMGeometry):
  1140. edited_object = self.collection.get_active()
  1141. # for now, if the Geometry is MultiGeo do not allow the editing
  1142. if edited_object.multigeo is True:
  1143. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1144. return
  1145. self.ui.update_obj_btn.setEnabled(True)
  1146. self.geo_editor.edit_fcgeometry(edited_object)
  1147. self.ui.g_editor_cmenu.setEnabled(True)
  1148. # set call source to the Editor we go into
  1149. self.call_source = 'geo_editor'
  1150. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  1151. sel_tab_widget_list = self.ui.selected_tab.findChildren(QtWidgets.QWidget)
  1152. for w in sel_tab_widget_list:
  1153. w.setEnabled(False)
  1154. elif isinstance(self.collection.get_active(), FlatCAMExcellon):
  1155. self.ui.update_obj_btn.setEnabled(True)
  1156. self.exc_editor.edit_exc_obj(self.collection.get_active())
  1157. self.ui.e_editor_cmenu.setEnabled(True)
  1158. # set call source to the Editor we go into
  1159. self.call_source = 'exc_editor'
  1160. else:
  1161. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1162. return
  1163. # make sure that we can't select another object while in Editor Mode:
  1164. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1165. # delete any selection shape that might be active as they are not relevant in Editor
  1166. self.delete_selection_shape()
  1167. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1168. self.inform.emit("[warning_notcl]Editor is activated ...")
  1169. def editor2object(self):
  1170. """
  1171. Transfers the Geometry or Excellon from the editor to the current object.
  1172. :return: None
  1173. """
  1174. edited_obj = self.collection.get_active()
  1175. obj_type = ""
  1176. if isinstance(edited_obj, FlatCAMGeometry):
  1177. obj_type = "Geometry"
  1178. self.geo_editor.update_fcgeometry(edited_obj)
  1179. self.geo_editor.update_options(edited_obj)
  1180. self.geo_editor.deactivate()
  1181. # edited_obj.on_tool_delete(all=True)
  1182. # edited_obj.on_tool_add(dia=edited_obj.options['cnctooldia'])
  1183. self.ui.corner_snap_btn.setEnabled(False)
  1184. self.ui.update_obj_btn.setEnabled(False)
  1185. self.ui.g_editor_cmenu.setEnabled(False)
  1186. self.ui.e_editor_cmenu.setEnabled(False)
  1187. # update the geo object options so it is including the bounding box values
  1188. try:
  1189. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1190. edited_obj.options['xmin'] = xmin
  1191. edited_obj.options['ymin'] = ymin
  1192. edited_obj.options['xmax'] = xmax
  1193. edited_obj.options['ymax'] = ymax
  1194. except AttributeError:
  1195. self.inform.emit("[warning] Object empty after edit.")
  1196. elif isinstance(edited_obj, FlatCAMExcellon):
  1197. obj_type = "Excellon"
  1198. self.exc_editor.update_exc_obj(edited_obj)
  1199. self.exc_editor.deactivate()
  1200. self.ui.corner_snap_btn.setEnabled(False)
  1201. self.ui.update_obj_btn.setEnabled(False)
  1202. self.ui.g_editor_cmenu.setEnabled(False)
  1203. self.ui.e_editor_cmenu.setEnabled(False)
  1204. else:
  1205. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1206. return
  1207. # restore the call_source to app
  1208. self.call_source = 'app'
  1209. edited_obj.plot()
  1210. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1211. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1212. # reset the Object UI to original settings
  1213. # edited_obj.set_ui(edited_obj.ui_type())
  1214. # edited_obj.build_ui()
  1215. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1216. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1217. def get_last_folder(self):
  1218. return self.defaults["global_last_folder"]
  1219. def get_last_save_folder(self):
  1220. return self.defaults["global_last_save_folder"]
  1221. def report_usage(self, resource):
  1222. """
  1223. Increments usage counter for the given resource
  1224. in self.defaults['global_stats'].
  1225. :param resource: Name of the resource.
  1226. :return: None
  1227. """
  1228. if resource in self.defaults['global_stats']:
  1229. self.defaults['global_stats'][resource] += 1
  1230. else:
  1231. self.defaults['global_stats'][resource] = 1
  1232. def init_tcl(self):
  1233. if hasattr(self,'tcl'):
  1234. # self.tcl = None
  1235. # TODO we need to clean non default variables and procedures here
  1236. # new object cannot be used here as it will not remember values created for next passes,
  1237. # because tcl was execudted in old instance of TCL
  1238. pass
  1239. else:
  1240. self.tcl = tk.Tcl()
  1241. self.setup_shell()
  1242. self.log.debug("TCL Shell has been initialized.")
  1243. # TODO: This shouldn't be here.
  1244. class TclErrorException(Exception):
  1245. """
  1246. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1247. """
  1248. pass
  1249. def shell_message(self, msg, show=False, error=False):
  1250. """
  1251. Shows a message on the FlatCAM Shell
  1252. :param msg: Message to display.
  1253. :param show: Opens the shell.
  1254. :param error: Shows the message as an error.
  1255. :return: None
  1256. """
  1257. if show:
  1258. self.ui.shell_dock.show()
  1259. try:
  1260. if error:
  1261. self.shell.append_error(msg + "\n")
  1262. else:
  1263. self.shell.append_output(msg + "\n")
  1264. except AttributeError:
  1265. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1266. def raise_tcl_unknown_error(self, unknownException):
  1267. """
  1268. Raise exception if is different type than TclErrorException
  1269. this is here mainly to show unknown errors inside TCL shell console.
  1270. :param unknownException:
  1271. :return:
  1272. """
  1273. if not isinstance(unknownException, self.TclErrorException):
  1274. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1275. else:
  1276. raise unknownException
  1277. def display_tcl_error(self, error, error_info=None):
  1278. """
  1279. escape bracket [ with \ otherwise there is error
  1280. "ERROR: missing close-bracket" instead of real error
  1281. :param error: it may be text or exception
  1282. :return: None
  1283. """
  1284. if isinstance(error, Exception):
  1285. exc_type, exc_value, exc_traceback = error_info
  1286. if not isinstance(error, self.TclErrorException):
  1287. show_trace = 1
  1288. else:
  1289. show_trace = int(self.defaults['global_verbose_error_level'])
  1290. if show_trace > 0:
  1291. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1292. trc_formated = []
  1293. for a in reversed(trc):
  1294. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1295. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1296. exc_type,
  1297. "\n".join(trc_formated))
  1298. else:
  1299. text = "%s" % error
  1300. else:
  1301. text = error
  1302. text = text.replace('[', '\\[').replace('"', '\\"')
  1303. self.tcl.eval('return -code error "%s"' % text)
  1304. def raise_tcl_error(self, text):
  1305. """
  1306. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1307. :param text: text of error
  1308. :return: raise exception
  1309. """
  1310. self.display_tcl_error(text)
  1311. raise self.TclErrorException(text)
  1312. def exec_command(self, text):
  1313. """
  1314. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1315. Also handles execution in separated threads
  1316. :param text:
  1317. :return: output if there was any
  1318. """
  1319. self.report_usage('exec_command')
  1320. result = self.exec_command_test(text, False)
  1321. #MS: added this method call so the geometry is updated once the TCL
  1322. #command is executed
  1323. self.plot_all()
  1324. return result
  1325. def exec_command_test(self, text, reraise=True):
  1326. """
  1327. Same as exec_command(...) with additional control over exceptions.
  1328. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1329. :param text: Input command
  1330. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1331. :return: Output from the command
  1332. """
  1333. text = str(text)
  1334. try:
  1335. self.shell.open_proccessing() # Disables input box.
  1336. result = self.tcl.eval(str(text))
  1337. if result != 'None':
  1338. self.shell.append_output(result + '\n')
  1339. except tk.TclError as e:
  1340. # This will display more precise answer if something in TCL shell fails
  1341. result = self.tcl.eval("set errorInfo")
  1342. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1343. self.shell.append_error('ERROR: ' + result + '\n')
  1344. # Show error in console and just return or in test raise exception
  1345. if reraise:
  1346. raise e
  1347. finally:
  1348. self.shell.close_proccessing()
  1349. pass
  1350. return result
  1351. # """
  1352. # Code below is unsused. Saved for later.
  1353. # """
  1354. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1355. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1356. # self.log.debug(parts)
  1357. # try:
  1358. # if parts[0] not in commands:
  1359. # self.shell.append_error("Unknown command\n")
  1360. # return
  1361. #
  1362. # #import inspect
  1363. # #inspect.getargspec(someMethod)
  1364. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1365. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1366. # self.shell.append_error(
  1367. # "Command %s takes %d arguments. %d given.\n" %
  1368. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1369. # )
  1370. # return
  1371. #
  1372. # cmdfcn = commands[parts[0]]["fcn"]
  1373. # cmdconv = commands[parts[0]]["converters"]
  1374. # if len(parts) - 1 > 0:
  1375. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1376. # else:
  1377. # retval = cmdfcn()
  1378. # retfcn = commands[parts[0]]["retfcn"]
  1379. # if retval and retfcn(retval):
  1380. # self.shell.append_output(retfcn(retval) + "\n")
  1381. #
  1382. # except Exception as e:
  1383. # #self.shell.append_error(''.join(traceback.format_exc()))
  1384. # #self.shell.append_error("?\n")
  1385. # self.shell.append_error(str(e) + "\n")
  1386. def info(self, msg):
  1387. """
  1388. Informs the user. Normally on the status bar, optionally
  1389. also on the shell.
  1390. :param msg: Text to write.
  1391. :return: None
  1392. """
  1393. # Type of message in brackets at the begining of the message.
  1394. match = re.search("\[([^\]]+)\](.*)", msg)
  1395. if match:
  1396. level = match.group(1)
  1397. msg_ = match.group(2)
  1398. self.ui.fcinfo.set_status(str(msg_), level=level)
  1399. if level == "error" or level == "warning":
  1400. self.shell_message(msg, error=True, show=True)
  1401. elif level == "error_notcl" or level == "warning_notcl":
  1402. self.shell_message(msg, error=True, show=False)
  1403. else:
  1404. self.shell_message(msg, error=False, show=False)
  1405. else:
  1406. self.ui.fcinfo.set_status(str(msg), level="info")
  1407. # make sure that if the message is to clear the infobar with a space
  1408. # is not printed over and over on the shell
  1409. if msg != '':
  1410. self.shell_message(msg)
  1411. def load_defaults(self):
  1412. """
  1413. Loads the aplication's default settings from defaults.json into
  1414. ``self.defaults``.
  1415. :return: None
  1416. """
  1417. try:
  1418. f = open(self.data_path + "/defaults.json")
  1419. options = f.read()
  1420. f.close()
  1421. except IOError:
  1422. self.log.error("Could not load defaults file.")
  1423. self.inform.emit("[error] Could not load defaults file.")
  1424. # in case the defaults file can't be loaded, show all toolbars
  1425. self.defaults["global_toolbar_view"] = 31
  1426. return
  1427. try:
  1428. defaults = json.loads(options)
  1429. except:
  1430. # in case the defaults file can't be loaded, show all toolbars
  1431. self.defaults["global_toolbar_view"] = 31
  1432. e = sys.exc_info()[0]
  1433. App.log.error(str(e))
  1434. self.inform.emit("[error] Failed to parse defaults file.")
  1435. return
  1436. self.defaults.update(defaults)
  1437. # restore the toolbar view
  1438. tb = self.defaults["global_toolbar_view"]
  1439. if tb & 1:
  1440. self.ui.toolbarfile.setVisible(True)
  1441. else:
  1442. self.ui.toolbarfile.setVisible(False)
  1443. if tb & 2:
  1444. self.ui.toolbargeo.setVisible(True)
  1445. else:
  1446. self.ui.toolbargeo.setVisible(False)
  1447. if tb & 4:
  1448. self.ui.toolbarview.setVisible(True)
  1449. else:
  1450. self.ui.toolbarview.setVisible(False)
  1451. if tb & 8:
  1452. self.ui.toolbartools.setVisible(True)
  1453. else:
  1454. self.ui.toolbartools.setVisible(False)
  1455. if tb & 16:
  1456. self.ui.snap_toolbar.setVisible(True)
  1457. else:
  1458. self.ui.snap_toolbar.setVisible(False)
  1459. def load_factory_defaults(self):
  1460. """
  1461. Loads the aplication's factory default settings from factory_defaults.json into
  1462. ``self.defaults``.
  1463. :return: None
  1464. """
  1465. try:
  1466. f = open(self.data_path + "/factory_defaults.json")
  1467. options = f.read()
  1468. f.close()
  1469. except IOError:
  1470. self.log.error("Could not load factory defaults file.")
  1471. self.inform.emit("[error] Could not load factory defaults file.")
  1472. return
  1473. try:
  1474. factory_defaults = json.loads(options)
  1475. except:
  1476. e = sys.exc_info()[0]
  1477. App.log.error(str(e))
  1478. self.inform.emit("[error] Failed to parse factory defaults file.")
  1479. return
  1480. self.defaults.update(factory_defaults)
  1481. self.inform.emit("[success] Imported Factory Defaults ...")
  1482. def load_user_defaults(self):
  1483. self.load_defaults()
  1484. self.inform.emit("[success] Loaded User Defaults ...")
  1485. def save_geometry(self, x, y, width, height, notebook_width):
  1486. self.defaults["global_def_win_x"] = x
  1487. self.defaults["global_def_win_y"] = y
  1488. self.defaults["global_def_win_w"] = width
  1489. self.defaults["global_def_win_h"] = height
  1490. self.defaults["def_notebook_width"] = notebook_width
  1491. self.save_defaults()
  1492. def message_dialog(self, title, message, kind="info"):
  1493. icon = {"info": QtWidgets.QMessageBox.Information,
  1494. "warning": QtWidgets.QMessageBox.Warning,
  1495. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1496. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1497. dlg.setText(message)
  1498. dlg.exec_()
  1499. def register_recent(self, kind, filename):
  1500. self.log.debug("register_recent()")
  1501. self.log.debug(" %s" % kind)
  1502. self.log.debug(" %s" % filename)
  1503. record = {'kind': str(kind), 'filename': str(filename)}
  1504. if record in self.recent:
  1505. return
  1506. self.recent.insert(0, record)
  1507. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1508. self.recent.pop()
  1509. try:
  1510. f = open(self.data_path + '/recent.json', 'w')
  1511. except IOError:
  1512. App.log.error("Failed to open recent items file for writing.")
  1513. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1514. return
  1515. #try:
  1516. json.dump(self.recent, f)
  1517. # except:
  1518. # App.log.error("Failed to write to recent items file.")
  1519. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1520. # f.close()
  1521. f.close()
  1522. # Re-buid the recent items menu
  1523. self.setup_recent_items()
  1524. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1525. """
  1526. Creates a new specalized FlatCAMObj and attaches it to the application,
  1527. this is, updates the GUI accordingly, any other records and plots it.
  1528. This method is thread-safe.
  1529. Notes:
  1530. * If the name is in use, the self.collection will modify it
  1531. when appending it to the collection. There is no need to handle
  1532. name conflicts here.
  1533. :param kind: The kind of object to create. One of 'gerber',
  1534. 'excellon', 'cncjob' and 'geometry'.
  1535. :type kind: str
  1536. :param name: Name for the object.
  1537. :type name: str
  1538. :param initialize: Function to run after creation of the object
  1539. but before it is attached to the application. The function is
  1540. called with 2 parameters: the new object and the App instance.
  1541. :type initialize: function
  1542. :return: None
  1543. :rtype: None
  1544. """
  1545. App.log.debug("new_object()")
  1546. self.plot = plot
  1547. self.autoselected = autoselected
  1548. t0 = time.time() # Debug
  1549. ## Create object
  1550. classdict = {
  1551. "gerber": FlatCAMGerber,
  1552. "excellon": FlatCAMExcellon,
  1553. "cncjob": FlatCAMCNCjob,
  1554. "geometry": FlatCAMGeometry
  1555. }
  1556. App.log.debug("Calling object constructor...")
  1557. obj = classdict[kind](name)
  1558. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1559. # Set options from "Project options" form
  1560. self.options_read_form()
  1561. # IMPORTANT
  1562. # The key names in defaults and options dictionary's are not random:
  1563. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1564. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1565. # the options from project options form into the self.options. After that, below, depending on the type of
  1566. # object that is created, it will strip the name of the object and the underline (if the original key was
  1567. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1568. # "toolchange"
  1569. for option in self.options:
  1570. if option.find(kind + "_") == 0:
  1571. oname = option[len(kind) + 1:]
  1572. obj.options[oname] = self.options[option]
  1573. # if kind == 'geometry':
  1574. # obj.tools = {}
  1575. # elif kind == 'cncjob':
  1576. # obj.cnc_tools = {}
  1577. # Initialize as per user request
  1578. # User must take care to implement initialize
  1579. # in a thread-safe way as is is likely that we
  1580. # have been invoked in a separate thread.
  1581. t1 = time.time()
  1582. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1583. try:
  1584. return_value = initialize(obj, self)
  1585. except Exception as e:
  1586. if str(e) == "Empty Geometry":
  1587. self.inform.emit("[error_notcl] Object (%s) failed because: %s" % (kind, str(e)))
  1588. else:
  1589. self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1590. return "fail"
  1591. t2 = time.time()
  1592. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1593. if return_value == 'fail':
  1594. return "fail"
  1595. # Check units and convert if necessary
  1596. # This condition CAN be true because initialize() can change obj.units
  1597. if self.options["units"].upper() != obj.units.upper():
  1598. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1599. obj.convert_units(self.options["units"])
  1600. t3 = time.time()
  1601. self.log.debug("%f seconds converting units." % (t3 - t2))
  1602. # Create the bounding box for the object and then add the results to the obj.options
  1603. try:
  1604. xmin, ymin, xmax, ymax = obj.bounds()
  1605. obj.options['xmin'] = xmin
  1606. obj.options['ymin'] = ymin
  1607. obj.options['xmax'] = xmax
  1608. obj.options['ymax'] = ymax
  1609. except:
  1610. log.warning("The object has no bounds properties.")
  1611. pass
  1612. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1613. # Move the object to the main thread and let the app know that it is available.
  1614. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1615. self.object_created.emit(obj, self.plot, self.autoselected)
  1616. return obj
  1617. def new_excellon_object(self):
  1618. self.new_object('excellon', 'new_e', lambda x, y: None)
  1619. def on_object_created(self, obj, plot, autoselect):
  1620. """
  1621. Event callback for object creation.
  1622. :param obj: The newly created FlatCAM object.
  1623. :return: None
  1624. """
  1625. t0 = time.time() # DEBUG
  1626. self.log.debug("on_object_created()")
  1627. # The Collection might change the name if there is a collision
  1628. self.collection.append(obj)
  1629. # after adding the object to the collection always update the list of objects that are in the collection
  1630. self.all_objects_list = self.collection.get_list()
  1631. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1632. self.new_object_available.emit(obj)
  1633. # update the SHELL auto-completer model with the name of the new object
  1634. self.myKeywords.append(obj.options['name'])
  1635. self.shell._edit.set_model_data(self.myKeywords)
  1636. if autoselect:
  1637. # select the just opened object but deselect the previous ones
  1638. self.collection.set_all_inactive()
  1639. self.collection.set_active(obj.options["name"])
  1640. def worker_task(obj):
  1641. with self.proc_container.new("Plotting"):
  1642. obj.plot()
  1643. t1 = time.time() # DEBUG
  1644. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1645. self.object_plotted.emit(obj)
  1646. # Send to worker
  1647. # self.worker.add_task(worker_task, [self])
  1648. if plot:
  1649. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1650. def on_object_changed(self, obj):
  1651. # update the bounding box data from obj.options
  1652. xmin, ymin, xmax, ymax = obj.bounds()
  1653. obj.options['xmin'] = xmin
  1654. obj.options['ymin'] = ymin
  1655. obj.options['xmax'] = xmax
  1656. obj.options['ymax'] = ymax
  1657. log.debug("Object changed, updating the bounding box data on self.options")
  1658. # delete the old selection shape
  1659. self.delete_selection_shape()
  1660. def on_object_plotted(self, obj):
  1661. self.on_zoom_fit(None)
  1662. def options_read_form(self):
  1663. for option in self.options_form_fields:
  1664. self.options[option] = self.options_form_fields[option].get_value()
  1665. def options_write_form(self):
  1666. for option in self.options:
  1667. self.options_write_form_field(option)
  1668. def options_write_form_field(self, field):
  1669. try:
  1670. self.options_form_fields[field].set_value(self.options[field])
  1671. except KeyError:
  1672. # Changed from error to debug. This allows to have data stored
  1673. # which is not user-editable.
  1674. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1675. pass
  1676. def on_about(self):
  1677. """
  1678. Displays the "about" dialog.
  1679. :return: None
  1680. """
  1681. self.report_usage("on_about")
  1682. version = self.version
  1683. version_date = self.version_date
  1684. class AboutDialog(QtWidgets.QDialog):
  1685. def __init__(self, parent=None):
  1686. QtWidgets.QDialog.__init__(self, parent)
  1687. # Icon and title
  1688. self.setWindowIcon(parent.app_icon)
  1689. self.setWindowTitle("FlatCAM")
  1690. layout1 = QtWidgets.QVBoxLayout()
  1691. self.setLayout(layout1)
  1692. layout2 = QtWidgets.QHBoxLayout()
  1693. layout1.addLayout(layout2)
  1694. logo = QtWidgets.QLabel()
  1695. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1696. layout2.addWidget(logo, stretch=0)
  1697. title = QtWidgets.QLabel(
  1698. "<font size=8><B>FlatCAM</B></font><BR>"
  1699. "Version %s (%s) - %s <BR>"
  1700. "<BR>"
  1701. "2D Computer-Aided Printed Circuit Board<BR>"
  1702. "Manufacturing.<BR>"
  1703. "<BR>"
  1704. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1705. "<BR>"
  1706. "<B>Contributors:</B><BR>"
  1707. "Denis Hayrullin<BR>"
  1708. "Kamil Sopko<BR>"
  1709. "Matthieu Berthomé<BR>"
  1710. "and many others found "
  1711. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1712. "<BR>"
  1713. "Development is done "
  1714. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1715. "DOWNLOAD area "
  1716. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1717. "" % (version, version_date, platform.architecture()[0])
  1718. )
  1719. title.setOpenExternalLinks(True)
  1720. layout2.addWidget(title, stretch=1)
  1721. layout3 = QtWidgets.QHBoxLayout()
  1722. layout1.addLayout(layout3)
  1723. layout3.addStretch()
  1724. okbtn = QtWidgets.QPushButton("Close")
  1725. layout3.addWidget(okbtn)
  1726. okbtn.clicked.connect(self.accept)
  1727. AboutDialog(self.ui).exec_()
  1728. def on_file_savedefaults(self):
  1729. """
  1730. Callback for menu item File->Save Defaults. Saves application default options
  1731. ``self.defaults`` to defaults.json.
  1732. :return: None
  1733. """
  1734. self.save_defaults()
  1735. def on_app_exit(self):
  1736. self.save_defaults()
  1737. log.debug("Application defaults saved ... Exit event.")
  1738. QtWidgets.qApp.quit()
  1739. def save_defaults(self, silent=False):
  1740. """
  1741. Saves application default options
  1742. ``self.defaults`` to defaults.json.
  1743. :return: None
  1744. """
  1745. self.report_usage("save_defaults")
  1746. # Read options from file
  1747. try:
  1748. f = open(self.data_path + "/defaults.json")
  1749. defaults_file_content = f.read()
  1750. f.close()
  1751. except:
  1752. e = sys.exc_info()[0]
  1753. App.log.error("Could not load defaults file.")
  1754. App.log.error(str(e))
  1755. self.inform.emit("[error_notcl] Could not load defaults file.")
  1756. return
  1757. try:
  1758. defaults = json.loads(defaults_file_content)
  1759. except:
  1760. e = sys.exc_info()[0]
  1761. App.log.error("Failed to parse defaults file.")
  1762. App.log.error(str(e))
  1763. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1764. return
  1765. # Update options
  1766. self.defaults_read_form()
  1767. defaults.update(self.defaults)
  1768. self.propagate_defaults(silent=True)
  1769. # Save update options
  1770. try:
  1771. f = open(self.data_path + "/defaults.json", "w")
  1772. json.dump(defaults, f)
  1773. f.close()
  1774. except:
  1775. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1776. return
  1777. # Save the toolbar view
  1778. tb_status = 0
  1779. if self.ui.toolbarfile.isVisible():
  1780. tb_status += 1
  1781. if self.ui.toolbargeo.isVisible():
  1782. tb_status += 2
  1783. if self.ui.toolbarview.isVisible():
  1784. tb_status += 4
  1785. if self.ui.toolbartools.isVisible():
  1786. tb_status += 8
  1787. if self.ui.snap_toolbar.isVisible():
  1788. tb_status += 16
  1789. self.defaults["global_toolbar_view"] = tb_status
  1790. if not silent:
  1791. self.inform.emit("[success]Defaults saved.")
  1792. def save_factory_defaults(self, silent=False):
  1793. """
  1794. Saves application factory default options
  1795. ``self.defaults`` to factory_defaults.json.
  1796. It's a one time job done just after the first install.
  1797. :return: None
  1798. """
  1799. self.report_usage("save_factory_defaults")
  1800. # Read options from file
  1801. try:
  1802. f_f_def = open(self.data_path + "/factory_defaults.json")
  1803. factory_defaults_file_content = f_f_def.read()
  1804. f_f_def.close()
  1805. except:
  1806. e = sys.exc_info()[0]
  1807. App.log.error("Could not load factory defaults file.")
  1808. App.log.error(str(e))
  1809. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  1810. return
  1811. try:
  1812. factory_defaults = json.loads(factory_defaults_file_content)
  1813. except:
  1814. e = sys.exc_info()[0]
  1815. App.log.error("Failed to parse factory defaults file.")
  1816. App.log.error(str(e))
  1817. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  1818. return
  1819. # Update options
  1820. self.defaults_read_form()
  1821. factory_defaults.update(self.defaults)
  1822. self.propagate_defaults(silent=True)
  1823. # Save update options
  1824. try:
  1825. f_f_def_s = open(self.data_path + "/factory_defaults.json", "w")
  1826. json.dump(factory_defaults, f_f_def_s)
  1827. f_f_def_s.close()
  1828. except:
  1829. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  1830. return
  1831. if silent is False:
  1832. self.inform.emit("Factory defaults saved.")
  1833. def final_save(self):
  1834. self.save_defaults()
  1835. log.debug("Application defaults saved ... Exit event.")
  1836. def on_toggle_shell(self):
  1837. """
  1838. toggle shell if is visible close it if closed open it
  1839. :return:
  1840. """
  1841. if self.ui.shell_dock.isVisible():
  1842. self.ui.shell_dock.hide()
  1843. else:
  1844. self.ui.shell_dock.show()
  1845. def on_edit_join(self, name=None):
  1846. """
  1847. Callback for Edit->Join. Joins the selected geometry objects into
  1848. a new one.
  1849. :return: None
  1850. """
  1851. obj_name_single = str(name) if name else "Combo_SingleGeo"
  1852. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  1853. tooldias = []
  1854. geo_type_list = []
  1855. objs = self.collection.get_selected()
  1856. for obj in objs:
  1857. geo_type_list.append(obj.multigeo)
  1858. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  1859. if len(set(geo_type_list)) != 1:
  1860. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  1861. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  1862. "convert from one to another and retry joining \n"
  1863. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  1864. "the result may not be what was expected. \n"
  1865. "Check the generated GCODE.")
  1866. return
  1867. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  1868. if True in geo_type_list:
  1869. def initialize(obj, app):
  1870. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  1871. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  1872. for v in obj.tools.values():
  1873. v['data']['name'] = obj_name_multi
  1874. self.new_object("geometry", obj_name_multi, initialize)
  1875. else:
  1876. def initialize(obj, app):
  1877. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  1878. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  1879. for v in obj.tools.values():
  1880. v['data']['name'] = obj_name_single
  1881. self.new_object("geometry", obj_name_single, initialize)
  1882. def on_edit_join_exc(self):
  1883. """
  1884. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  1885. a new one.
  1886. :return: None
  1887. """
  1888. objs = self.collection.get_selected()
  1889. for obj in objs:
  1890. if not isinstance(obj, FlatCAMExcellon):
  1891. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  1892. return
  1893. def initialize(obj, app):
  1894. FlatCAMExcellon.merge(objs, obj)
  1895. self.new_object("excellon", 'Combo_Excellon', initialize)
  1896. def on_convert_singlegeo_to_multigeo(self):
  1897. obj = self.collection.get_active()
  1898. if obj is None:
  1899. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  1900. return
  1901. if not isinstance(obj, FlatCAMGeometry):
  1902. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  1903. return
  1904. obj.multigeo = True
  1905. for tooluid, dict_value in obj.tools.items():
  1906. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  1907. if not isinstance(obj.solid_geometry, list):
  1908. obj.solid_geometry = [obj.solid_geometry]
  1909. obj.solid_geometry[:] = []
  1910. obj.plot()
  1911. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  1912. def on_convert_multigeo_to_singlegeo(self):
  1913. obj = self.collection.get_active()
  1914. if obj is None:
  1915. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  1916. return
  1917. if not isinstance(obj, FlatCAMGeometry):
  1918. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  1919. return
  1920. obj.multigeo = False
  1921. total_solid_geometry = []
  1922. for tooluid, dict_value in obj.tools.items():
  1923. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  1924. # clear the original geometry
  1925. dict_value['solid_geometry'][:] = []
  1926. obj.solid_geometry = deepcopy(total_solid_geometry)
  1927. obj.plot()
  1928. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  1929. def on_options_dict_change(self, field):
  1930. self.options_write_form_field(field)
  1931. if field == "units":
  1932. self.set_screen_units(self.options['units'])
  1933. def on_defaults_dict_change(self, field):
  1934. self.defaults_write_form_field(field)
  1935. def set_screen_units(self, units):
  1936. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  1937. def on_toggle_units(self):
  1938. """
  1939. Callback for the Units radio-button change in the Options tab.
  1940. Changes the application's default units or the current project's units.
  1941. If changing the project's units, the change propagates to all of
  1942. the objects in the project.
  1943. :return: None
  1944. """
  1945. self.report_usage("on_toggle_units")
  1946. if self.toggle_units_ignore:
  1947. return
  1948. # If option is the same, then ignore
  1949. if self.general_options_form.general_group.units_radio.get_value().upper() == self.options["units"].upper():
  1950. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  1951. return
  1952. # Options to scale
  1953. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1954. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','gerber_nccoverlap',
  1955. 'gerber_nccmargin','gerber_cutouttooldia','gerber_cutoutgapsize','gerber_cutoutmargin',
  1956. 'gerber_noncoppermargin','gerber_bboxmargin',
  1957. 'excellon_drillz', "excellon_toolchangexy",
  1958. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  1959. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  1960. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  1961. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap', 'geometry_toolchangexy',
  1962. 'geometry_toolchangez',
  1963. 'geometry_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  1964. def scale_options(sfactor):
  1965. for dim in dimensions:
  1966. if dim == 'excellon_toolchangexy':
  1967. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  1968. coords_xy[0] *= sfactor
  1969. coords_xy[1] *= sfactor
  1970. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1971. elif dim == 'geometry_toolchangexy':
  1972. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  1973. coords_xy[0] *= sfactor
  1974. coords_xy[1] *= sfactor
  1975. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1976. else:
  1977. self.options[dim] *= sfactor
  1978. # The scaling factor depending on choice of units.
  1979. factor = 1/25.4
  1980. if self.general_options_form.general_group.units_radio.get_value().upper() == 'MM':
  1981. factor = 25.4
  1982. # Changing project units. Warn user.
  1983. msgbox = QtWidgets.QMessageBox()
  1984. msgbox.setText("<B>Change project units ...</B>")
  1985. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  1986. "properties of all objects to be scaled accordingly. Continue?")
  1987. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  1988. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  1989. response = msgbox.exec_()
  1990. if response == QtWidgets.QMessageBox.Ok:
  1991. self.options_read_form()
  1992. scale_options(factor)
  1993. self.options_write_form()
  1994. # change this only if the workspace is active
  1995. if self.defaults['global_workspace'] is True:
  1996. self.plotcanvas.draw_workspace()
  1997. # adjust the grid values on the main toolbar
  1998. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  1999. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2000. for obj in self.collection.get_list():
  2001. units = self.general_options_form.general_group.units_radio.get_value().upper()
  2002. obj.convert_units(units)
  2003. # make that the properties stored in the object are also updated
  2004. self.object_changed.emit(obj)
  2005. obj.build_ui()
  2006. current = self.collection.get_active()
  2007. if current is not None:
  2008. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2009. if not isinstance(current, FlatCAMGeometry):
  2010. current.to_form()
  2011. self.plot_all()
  2012. else:
  2013. # Undo toggling
  2014. self.toggle_units_ignore = True
  2015. if self.general_options_form.general_group.units_radio.get_value().upper() == 'MM':
  2016. self.general_options_form.general_group.units_radio.set_value('IN')
  2017. else:
  2018. self.general_options_form.general_group.units_radio.set_value('MM')
  2019. self.toggle_units_ignore = False
  2020. self.options_read_form()
  2021. self.inform.emit("Converted units to %s" % self.options["units"])
  2022. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2023. self.set_screen_units(self.options["units"])
  2024. def on_toggle_axis(self):
  2025. if self.toggle_axis is False:
  2026. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2027. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2028. self.plotcanvas.redraw()
  2029. self.toggle_axis = True
  2030. else:
  2031. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2032. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2033. self.plotcanvas.redraw()
  2034. self.toggle_axis = False
  2035. def on_options_combo_change(self, sel):
  2036. """
  2037. Called when the combo box to choose between application defaults and
  2038. project option changes value. The corresponding variables are
  2039. copied to the UI.
  2040. :param sel: The option index that was chosen.
  2041. :return: None
  2042. """
  2043. # combo_sel = self.ui.notebook.combo_options.get_active()
  2044. App.log.debug("Options --> %s" % sel)
  2045. # form = [self.defaults_form, self.options_form][sel]
  2046. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2047. if sel == 0:
  2048. self.gen_form = self.general_defaults_form
  2049. self.ger_form = self.gerber_defaults_form
  2050. self.exc_form = self.excellon_defaults_form
  2051. self.geo_form = self.geometry_defaults_form
  2052. self.cnc_form = self.cncjob_defaults_form
  2053. elif sel == 1:
  2054. self.gen_form = self.general_options_form
  2055. self.ger_form = self.gerber_options_form
  2056. self.exc_form = self.excellon_options_form
  2057. self.geo_form = self.geometry_options_form
  2058. self.cnc_form = self.cncjob_options_form
  2059. else:
  2060. return
  2061. try:
  2062. self.ui.general_scroll_area.takeWidget()
  2063. except:
  2064. self.log.debug("Nothing to remove")
  2065. self.ui.general_scroll_area.setWidget(self.gen_form)
  2066. self.gen_form.show()
  2067. try:
  2068. self.ui.gerber_scroll_area.takeWidget()
  2069. except:
  2070. self.log.debug("Nothing to remove")
  2071. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2072. self.ger_form.show()
  2073. try:
  2074. self.ui.excellon_scroll_area.takeWidget()
  2075. except:
  2076. self.log.debug("Nothing to remove")
  2077. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2078. self.exc_form.show()
  2079. try:
  2080. self.ui.geometry_scroll_area.takeWidget()
  2081. except:
  2082. self.log.debug("Nothing to remove")
  2083. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2084. self.geo_form.show()
  2085. try:
  2086. self.ui.cncjob_scroll_area.takeWidget()
  2087. except:
  2088. self.log.debug("Nothing to remove")
  2089. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2090. self.cnc_form.show()
  2091. self.log.debug("Finished GUI form initialization.")
  2092. # self.options2form()
  2093. def on_excellon_defaults_button(self):
  2094. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2095. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2096. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2097. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2098. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2099. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2100. log.debug("Excellon app defaults loaded ...")
  2101. def on_excellon_options_button(self):
  2102. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2103. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2104. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2105. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2106. self.options_form_fields["excellon_zeros"].set_value('L')
  2107. self.options_form_fields["excellon_units"].set_value('INCH')
  2108. log.debug("Excellon options defaults loaded ...")
  2109. # Setting plot colors handlers
  2110. def on_pf_color_entry(self):
  2111. self.defaults['global_plot_fill'] = self.general_defaults_form.general_group.pf_color_entry.get_value()[:7] + \
  2112. self.defaults['global_plot_fill'][7:9]
  2113. self.general_defaults_form.general_group.pf_color_button.setStyleSheet(
  2114. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2115. def on_pf_color_button(self):
  2116. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2117. c_dialog = QtWidgets.QColorDialog()
  2118. plot_fill_color = c_dialog.getColor(initial=current_color)
  2119. if plot_fill_color.isValid() is False:
  2120. return
  2121. self.general_defaults_form.general_group.pf_color_button.setStyleSheet(
  2122. "background-color:%s" % str(plot_fill_color.name()))
  2123. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2124. self.general_defaults_form.general_group.pf_color_entry.set_value(new_val)
  2125. self.defaults['global_plot_fill'] = new_val
  2126. def on_pf_color_spinner(self):
  2127. spinner_value = self.general_defaults_form.general_group.pf_color_alpha_spinner.value()
  2128. self.general_defaults_form.general_group.pf_color_alpha_slider.setValue(spinner_value)
  2129. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2130. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2131. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2132. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2133. def on_pf_color_slider(self):
  2134. slider_value = self.general_defaults_form.general_group.pf_color_alpha_slider.value()
  2135. self.general_defaults_form.general_group.pf_color_alpha_spinner.setValue(slider_value)
  2136. def on_pl_color_entry(self):
  2137. self.defaults['global_plot_line'] = self.general_defaults_form.general_group.pl_color_entry.get_value()[:7] + \
  2138. self.defaults['global_plot_line'][7:9]
  2139. self.general_defaults_form.general_group.pl_color_button.setStyleSheet(
  2140. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2141. def on_pl_color_button(self):
  2142. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2143. # print(current_color)
  2144. c_dialog = QtWidgets.QColorDialog()
  2145. plot_line_color = c_dialog.getColor(initial=current_color)
  2146. if plot_line_color.isValid() is False:
  2147. return
  2148. self.general_defaults_form.general_group.pl_color_button.setStyleSheet(
  2149. "background-color:%s" % str(plot_line_color.name()))
  2150. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2151. self.general_defaults_form.general_group.pl_color_entry.set_value(new_val_line)
  2152. self.defaults['global_plot_line'] = new_val_line
  2153. # Setting selection colors (left - right) handlers
  2154. def on_sf_color_entry(self):
  2155. self.defaults['global_sel_fill'] = self.general_defaults_form.general_group.sf_color_entry.get_value()[:7] + \
  2156. self.defaults['global_sel_fill'][7:9]
  2157. self.general_defaults_form.general_group.sf_color_button.setStyleSheet(
  2158. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2159. def on_sf_color_button(self):
  2160. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2161. c_dialog = QtWidgets.QColorDialog()
  2162. plot_fill_color = c_dialog.getColor(initial=current_color)
  2163. if plot_fill_color.isValid() is False:
  2164. return
  2165. self.general_defaults_form.general_group.sf_color_button.setStyleSheet(
  2166. "background-color:%s" % str(plot_fill_color.name()))
  2167. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2168. self.general_defaults_form.general_group.sf_color_entry.set_value(new_val)
  2169. self.defaults['global_sel_fill'] = new_val
  2170. def on_sf_color_spinner(self):
  2171. spinner_value = self.general_defaults_form.general_group.sf_color_alpha_spinner.value()
  2172. self.general_defaults_form.general_group.sf_color_alpha_slider.setValue(spinner_value)
  2173. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2174. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2175. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2176. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2177. def on_sf_color_slider(self):
  2178. slider_value = self.general_defaults_form.general_group.sf_color_alpha_slider.value()
  2179. self.general_defaults_form.general_group.sf_color_alpha_spinner.setValue(slider_value)
  2180. def on_sl_color_entry(self):
  2181. self.defaults['global_sel_line'] = self.general_defaults_form.general_group.sl_color_entry.get_value()[:7] + \
  2182. self.defaults['global_sel_line'][7:9]
  2183. self.general_defaults_form.general_group.sl_color_button.setStyleSheet(
  2184. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2185. def on_sl_color_button(self):
  2186. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2187. c_dialog = QtWidgets.QColorDialog()
  2188. plot_line_color = c_dialog.getColor(initial=current_color)
  2189. if plot_line_color.isValid() is False:
  2190. return
  2191. self.general_defaults_form.general_group.sl_color_button.setStyleSheet(
  2192. "background-color:%s" % str(plot_line_color.name()))
  2193. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2194. self.general_defaults_form.general_group.sl_color_entry.set_value(new_val_line)
  2195. self.defaults['global_sel_line'] = new_val_line
  2196. # Setting selection colors (right - left) handlers
  2197. def on_alt_sf_color_entry(self):
  2198. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_group \
  2199. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2200. self.general_defaults_form.general_group.alt_sf_color_button.setStyleSheet(
  2201. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2202. def on_alt_sf_color_button(self):
  2203. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2204. c_dialog = QtWidgets.QColorDialog()
  2205. plot_fill_color = c_dialog.getColor(initial=current_color)
  2206. if plot_fill_color.isValid() is False:
  2207. return
  2208. self.general_defaults_form.general_group.alt_sf_color_button.setStyleSheet(
  2209. "background-color:%s" % str(plot_fill_color.name()))
  2210. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2211. self.general_defaults_form.general_group.alt_sf_color_entry.set_value(new_val)
  2212. self.defaults['global_alt_sel_fill'] = new_val
  2213. def on_alt_sf_color_spinner(self):
  2214. spinner_value = self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.value()
  2215. self.general_defaults_form.general_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2216. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2217. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2218. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2219. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2220. def on_alt_sf_color_slider(self):
  2221. slider_value = self.general_defaults_form.general_group.alt_sf_color_alpha_slider.value()
  2222. self.general_defaults_form.general_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2223. def on_alt_sl_color_entry(self):
  2224. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_group \
  2225. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2226. self.general_defaults_form.general_group.alt_sl_color_button.setStyleSheet(
  2227. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2228. def on_alt_sl_color_button(self):
  2229. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2230. c_dialog = QtWidgets.QColorDialog()
  2231. plot_line_color = c_dialog.getColor(initial=current_color)
  2232. if plot_line_color.isValid() is False:
  2233. return
  2234. self.general_defaults_form.general_group.alt_sl_color_button.setStyleSheet(
  2235. "background-color:%s" % str(plot_line_color.name()))
  2236. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2237. self.general_defaults_form.general_group.alt_sl_color_entry.set_value(new_val_line)
  2238. self.defaults['global_alt_sel_line'] = new_val_line
  2239. # Setting Editor colors
  2240. def on_draw_color_entry(self):
  2241. self.defaults['global_draw_color'] = self.general_defaults_form.general_group \
  2242. .draw_color_entry.get_value()
  2243. self.general_defaults_form.general_group.draw_color_button.setStyleSheet(
  2244. "background-color:%s" % str(self.defaults['global_draw_color']))
  2245. def on_draw_color_button(self):
  2246. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2247. c_dialog = QtWidgets.QColorDialog()
  2248. draw_color = c_dialog.getColor(initial=current_color)
  2249. if draw_color.isValid() is False:
  2250. return
  2251. self.general_defaults_form.general_group.draw_color_button.setStyleSheet(
  2252. "background-color:%s" % str(draw_color.name()))
  2253. new_val = str(draw_color.name())
  2254. self.general_defaults_form.general_group.draw_color_entry.set_value(new_val)
  2255. self.defaults['global_draw_color'] = new_val
  2256. def on_sel_draw_color_entry(self):
  2257. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_group \
  2258. .sel_draw_color_entry.get_value()
  2259. self.general_defaults_form.general_group.sel_draw_color_button.setStyleSheet(
  2260. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2261. def on_sel_draw_color_button(self):
  2262. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2263. c_dialog = QtWidgets.QColorDialog()
  2264. sel_draw_color = c_dialog.getColor(initial=current_color)
  2265. if sel_draw_color.isValid() is False:
  2266. return
  2267. self.general_defaults_form.general_group.sel_draw_color_button.setStyleSheet(
  2268. "background-color:%s" % str(sel_draw_color.name()))
  2269. new_val_sel = str(sel_draw_color.name())
  2270. self.general_defaults_form.general_group.sel_draw_color_entry.set_value(new_val_sel)
  2271. self.defaults['global_sel_draw_color'] = new_val_sel
  2272. def on_workspace_modified(self):
  2273. self.save_defaults(silent=True)
  2274. self.plotcanvas.draw_workspace()
  2275. def on_workspace(self):
  2276. if self.general_defaults_form.general_group.workspace_cb.isChecked():
  2277. self.plotcanvas.restore_workspace()
  2278. else:
  2279. self.plotcanvas.delete_workspace()
  2280. self.save_defaults(silent=True)
  2281. def on_workspace_menu(self):
  2282. if self.general_defaults_form.general_group.workspace_cb.isChecked():
  2283. self.general_defaults_form.general_group.workspace_cb.setChecked(False)
  2284. else:
  2285. self.general_defaults_form.general_group.workspace_cb.setChecked(True)
  2286. self.on_workspace()
  2287. def on_save_button(self):
  2288. self.save_defaults(silent=False)
  2289. # load the defaults so they are updated into the app
  2290. self.load_defaults()
  2291. # Re-fresh project options
  2292. self.on_options_app2project()
  2293. def handleOpen(self):
  2294. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2295. "All Files (*.*)"
  2296. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2297. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2298. if path:
  2299. file = QtCore.QFile(path)
  2300. if file.open(QtCore.QIODevice.ReadOnly):
  2301. stream = QtCore.QTextStream(file)
  2302. self.gcode_edited = stream.readAll()
  2303. self.ui.code_editor.setPlainText(self.gcode_edited)
  2304. file.close()
  2305. def handlePrint(self):
  2306. dialog = QtPrintSupport.QPrintDialog()
  2307. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2308. self.ui.code_editor.document().print_(dialog.printer())
  2309. def handlePreview(self):
  2310. dialog = QtPrintSupport.QPrintPreviewDialog()
  2311. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2312. dialog.exec_()
  2313. def handleTextChanged(self):
  2314. # enable = not self.ui.code_editor.document().isEmpty()
  2315. # self.ui.buttonPrint.setEnabled(enable)
  2316. # self.ui.buttonPreview.setEnabled(enable)
  2317. pass
  2318. def handleSaveGCode(self):
  2319. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2320. "All Files (*.*)"
  2321. try:
  2322. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2323. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2324. except TypeError:
  2325. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2326. try:
  2327. my_gcode = self.ui.code_editor.toPlainText()
  2328. with open(filename, 'w') as f:
  2329. for line in my_gcode:
  2330. f.write(line)
  2331. except FileNotFoundError:
  2332. self.inform.emit("[WARNING] No such file or directory")
  2333. return
  2334. # Just for adding it to the recent files list.
  2335. self.file_opened.emit("cncjob", filename)
  2336. self.file_saved.emit("cncjob", filename)
  2337. self.inform.emit("Saved to: " + filename)
  2338. def handleFindGCode(self):
  2339. flags = QtGui.QTextDocument.FindCaseSensitively
  2340. text_to_be_found = self.ui.entryFind.get_value()
  2341. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2342. if r is False:
  2343. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2344. def handleReplaceGCode(self):
  2345. old = self.ui.entryFind.get_value()
  2346. new = self.ui.entryReplace.get_value()
  2347. if self.ui.sel_all_cb.isChecked():
  2348. while True:
  2349. cursor = self.ui.code_editor.textCursor()
  2350. cursor.beginEditBlock()
  2351. flags = QtGui.QTextDocument.FindCaseSensitively
  2352. # self.ui.editor is the QPlainTextEdit
  2353. r = self.ui.code_editor.find(str(old), flags)
  2354. if r:
  2355. qc = self.ui.code_editor.textCursor()
  2356. if qc.hasSelection():
  2357. qc.insertText(new)
  2358. else:
  2359. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2360. break
  2361. # Mark end of undo block
  2362. cursor.endEditBlock()
  2363. else:
  2364. cursor = self.ui.code_editor.textCursor()
  2365. cursor.beginEditBlock()
  2366. qc = self.ui.code_editor.textCursor()
  2367. if qc.hasSelection():
  2368. qc.insertText(new)
  2369. # Mark end of undo block
  2370. cursor.endEditBlock()
  2371. def on_new_geometry(self):
  2372. def initialize(obj, self):
  2373. obj.multitool = False
  2374. self.new_object('geometry', 'new_g', initialize)
  2375. self.plot_all()
  2376. def on_delete(self):
  2377. """
  2378. Delete the currently selected FlatCAMObjs.
  2379. :return: None
  2380. """
  2381. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2382. # a geometry object before we update it.
  2383. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2384. if self.collection.get_active():
  2385. self.log.debug("on_delete()")
  2386. self.report_usage("on_delete")
  2387. while (self.collection.get_active()):
  2388. self.delete_first_selected()
  2389. self.inform.emit("Object(s) deleted ...")
  2390. # make sure that the selection shape is deleted, too
  2391. self.delete_selection_shape()
  2392. else:
  2393. self.inform.emit("Failed. No object(s) selected...")
  2394. else:
  2395. self.inform.emit("Save the work in Editor and try again ...")
  2396. def on_set_origin(self):
  2397. """
  2398. Set the origin to the left mouse click position
  2399. :return: None
  2400. """
  2401. #display the message for the user
  2402. #and ask him to click on the desired position
  2403. self.inform.emit('Click to set the origin ...')
  2404. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2405. def on_jump_to(self):
  2406. """
  2407. Jump to a location by setting the mouse cursor location
  2408. :return:
  2409. """
  2410. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2411. if dia_box.ok is True:
  2412. try:
  2413. location = eval(dia_box.location)
  2414. if not isinstance(location, tuple):
  2415. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2416. return
  2417. except:
  2418. return
  2419. else:
  2420. return
  2421. self.plotcanvas.fit_center(loc=location)
  2422. cursor = QtGui.QCursor()
  2423. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2424. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2425. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2426. self.inform.emit("Done.")
  2427. def on_copy_object(self):
  2428. def initialize(obj_init, app):
  2429. obj_init.solid_geometry = obj.solid_geometry
  2430. if obj.tools:
  2431. obj_init.tools = obj.tools
  2432. def initialize_excellon(obj_init, app):
  2433. obj_init.tools = obj.tools
  2434. # drills are offset, so they need to be deep copied
  2435. obj_init.drills = deepcopy(obj.drills)
  2436. obj_init.create_geometry()
  2437. for obj in self.collection.get_selected():
  2438. obj_name = obj.options["name"]
  2439. try:
  2440. if isinstance(obj, FlatCAMExcellon):
  2441. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2442. elif isinstance(obj,FlatCAMGerber):
  2443. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2444. elif isinstance(obj,FlatCAMGeometry):
  2445. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2446. except Exception as e:
  2447. return "Operation failed: %s" % str(e)
  2448. def on_copy_object2(self, custom_name):
  2449. def initialize_geometry(obj_init, app):
  2450. obj_init.solid_geometry = obj.solid_geometry
  2451. if obj.tools:
  2452. obj_init.tools = obj.tools
  2453. def initialize_gerber(obj_init, app):
  2454. obj_init.solid_geometry = obj.solid_geometry
  2455. obj_init.apertures = deepcopy(obj.apertures)
  2456. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2457. def initialize_excellon(obj_init, app):
  2458. obj_init.tools = obj.tools
  2459. # drills are offset, so they need to be deep copied
  2460. obj_init.drills = deepcopy(obj.drills)
  2461. obj_init.create_geometry()
  2462. for obj in self.collection.get_selected():
  2463. obj_name = obj.options["name"]
  2464. try:
  2465. if isinstance(obj, FlatCAMExcellon):
  2466. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2467. elif isinstance(obj,FlatCAMGerber):
  2468. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2469. elif isinstance(obj,FlatCAMGeometry):
  2470. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2471. except Exception as e:
  2472. return "Operation failed: %s" % str(e)
  2473. def on_rename_object(self, text):
  2474. named_obj = self.collection.get_active()
  2475. for obj in named_obj:
  2476. if obj is list:
  2477. self.on_rename_object(text)
  2478. else:
  2479. try:
  2480. obj.options['name'] = text
  2481. except:
  2482. log.warning("Could not rename the object in the list")
  2483. def on_copy_object_as_geometry(self):
  2484. def initialize(obj_init, app):
  2485. obj_init.solid_geometry = obj.solid_geometry
  2486. if obj.tools:
  2487. obj_init.tools = obj.tools
  2488. def initialize_excellon(obj, app):
  2489. objs = self.collection.get_selected()
  2490. FlatCAMGeometry.merge(objs, obj)
  2491. for obj in self.collection.get_selected():
  2492. obj_name = obj.options["name"]
  2493. try:
  2494. if isinstance(obj, FlatCAMExcellon):
  2495. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2496. else:
  2497. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2498. except Exception as e:
  2499. return "Operation failed: %s" % str(e)
  2500. def on_set_zero_click(self, event):
  2501. #this function will be available only for mouse left click
  2502. pos =[]
  2503. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2504. if event.button == 1:
  2505. if self.grid_status() == True:
  2506. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2507. else:
  2508. pos = pos_canvas
  2509. x = 0 - pos[0]
  2510. y = 0 - pos[1]
  2511. for obj in self.collection.get_list():
  2512. obj.offset((x,y))
  2513. self.object_changed.emit(obj)
  2514. # obj.plot()
  2515. self.plot_all()
  2516. self.inform.emit('[success] Origin set ...')
  2517. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2518. def on_selectall(self):
  2519. # delete the possible selection box around a possible selected object
  2520. self.delete_selection_shape()
  2521. for name in self.collection.get_names():
  2522. self.collection.set_active(name)
  2523. curr_sel_obj = self.collection.get_by_name(name)
  2524. # create the selection box around the selected object
  2525. self.draw_selection_shape(curr_sel_obj)
  2526. def on_preferences(self):
  2527. # add the tab if it was closed
  2528. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2529. # delete the absolute and relative position and messages in the infobar
  2530. self.ui.position_label.setText("")
  2531. self.ui.rel_position_label.setText("")
  2532. # Switch plot_area to preferences page
  2533. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2534. self.ui.show()
  2535. def on_flipy(self):
  2536. obj_list = self.collection.get_selected()
  2537. xminlist = []
  2538. yminlist = []
  2539. xmaxlist = []
  2540. ymaxlist = []
  2541. if not obj_list:
  2542. self.inform.emit("[warning_notcl] No object selected.")
  2543. msg = "Please Select an object to flip!"
  2544. warningbox = QtWidgets.QMessageBox()
  2545. warningbox.setText(msg)
  2546. warningbox.setWindowTitle("Warning ...")
  2547. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2548. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2549. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2550. warningbox.exec_()
  2551. else:
  2552. try:
  2553. # first get a bounding box to fit all
  2554. for obj in obj_list:
  2555. xmin, ymin, xmax, ymax = obj.bounds()
  2556. xminlist.append(xmin)
  2557. yminlist.append(ymin)
  2558. xmaxlist.append(xmax)
  2559. ymaxlist.append(ymax)
  2560. # get the minimum x,y and maximum x,y for all objects selected
  2561. xminimal = min(xminlist)
  2562. yminimal = min(yminlist)
  2563. xmaximal = max(xmaxlist)
  2564. ymaximal = max(ymaxlist)
  2565. px = 0.5 * (xminimal + xmaximal)
  2566. py = 0.5 * (yminimal + ymaximal)
  2567. # execute mirroring
  2568. for obj in obj_list:
  2569. obj.mirror('X', [px, py])
  2570. obj.plot()
  2571. self.object_changed.emit(obj)
  2572. except Exception as e:
  2573. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2574. return
  2575. def on_flipx(self):
  2576. obj_list = self.collection.get_selected()
  2577. xminlist = []
  2578. yminlist = []
  2579. xmaxlist = []
  2580. ymaxlist = []
  2581. if not obj_list:
  2582. self.inform.emit("[warning_notcl] No object selected.")
  2583. msg = "Please Select an object to flip!"
  2584. warningbox = QtWidgets.QMessageBox()
  2585. warningbox.setText(msg)
  2586. warningbox.setWindowTitle("Warning ...")
  2587. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2588. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2589. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2590. warningbox.exec_()
  2591. else:
  2592. try:
  2593. # first get a bounding box to fit all
  2594. for obj in obj_list:
  2595. xmin, ymin, xmax, ymax = obj.bounds()
  2596. xminlist.append(xmin)
  2597. yminlist.append(ymin)
  2598. xmaxlist.append(xmax)
  2599. ymaxlist.append(ymax)
  2600. # get the minimum x,y and maximum x,y for all objects selected
  2601. xminimal = min(xminlist)
  2602. yminimal = min(yminlist)
  2603. xmaximal = max(xmaxlist)
  2604. ymaximal = max(ymaxlist)
  2605. px = 0.5 * (xminimal + xmaximal)
  2606. py = 0.5 * (yminimal + ymaximal)
  2607. # execute mirroring
  2608. for obj in obj_list:
  2609. obj.mirror('Y', [px, py])
  2610. obj.plot()
  2611. self.object_changed.emit(obj)
  2612. except Exception as e:
  2613. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2614. return
  2615. def on_rotate(self, silent=False, preset=None):
  2616. obj_list = self.collection.get_selected()
  2617. xminlist = []
  2618. yminlist = []
  2619. xmaxlist = []
  2620. ymaxlist = []
  2621. if not obj_list:
  2622. self.inform.emit("[warning_notcl] No object selected.")
  2623. msg = "Please Select an object to rotate!"
  2624. warningbox = QtWidgets.QMessageBox()
  2625. warningbox.setText(msg)
  2626. warningbox.setWindowTitle("Warning ...")
  2627. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2628. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2629. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2630. warningbox.exec_()
  2631. else:
  2632. if silent is False:
  2633. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2634. min=-360, max=360, decimals=3)
  2635. num, ok = rotatebox.get_value()
  2636. else:
  2637. num = preset
  2638. ok = True
  2639. if ok:
  2640. try:
  2641. # first get a bounding box to fit all
  2642. for obj in obj_list:
  2643. xmin, ymin, xmax, ymax = obj.bounds()
  2644. xminlist.append(xmin)
  2645. yminlist.append(ymin)
  2646. xmaxlist.append(xmax)
  2647. ymaxlist.append(ymax)
  2648. # get the minimum x,y and maximum x,y for all objects selected
  2649. xminimal = min(xminlist)
  2650. yminimal = min(yminlist)
  2651. xmaximal = max(xmaxlist)
  2652. ymaximal = max(ymaxlist)
  2653. px = 0.5 * (xminimal + xmaximal)
  2654. py = 0.5 * (yminimal + ymaximal)
  2655. for sel_obj in obj_list:
  2656. sel_obj.rotate(-num, point=(px, py))
  2657. sel_obj.plot()
  2658. self.object_changed.emit(sel_obj)
  2659. except Exception as e:
  2660. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  2661. return
  2662. def on_skewx(self):
  2663. obj_list = self.collection.get_selected()
  2664. xminlist = []
  2665. yminlist = []
  2666. if not obj_list:
  2667. self.inform.emit("[warning_notcl] No object selected.")
  2668. msg = "Please Select an object to skew/shear!"
  2669. warningbox = QtWidgets.QMessageBox()
  2670. warningbox.setText(msg)
  2671. warningbox.setWindowTitle("Warning ...")
  2672. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2673. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2674. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2675. warningbox.exec_()
  2676. else:
  2677. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2678. min=-360, max=360, decimals=3)
  2679. num, ok = skewxbox.get_value()
  2680. if ok:
  2681. # first get a bounding box to fit all
  2682. for obj in obj_list:
  2683. xmin, ymin, xmax, ymax = obj.bounds()
  2684. xminlist.append(xmin)
  2685. yminlist.append(ymin)
  2686. # get the minimum x,y and maximum x,y for all objects selected
  2687. xminimal = min(xminlist)
  2688. yminimal = min(yminlist)
  2689. for obj in obj_list:
  2690. obj.skew(num, 0, point=(xminimal, yminimal))
  2691. obj.plot()
  2692. self.object_changed.emit(obj)
  2693. def on_skewy(self):
  2694. obj_list = self.collection.get_selected()
  2695. xminlist = []
  2696. yminlist = []
  2697. if not obj_list:
  2698. self.inform.emit("[warning_notcl] No object selected.")
  2699. msg = "Please Select an object to skew/shear!"
  2700. warningbox = QtWidgets.QMessageBox()
  2701. warningbox.setText(msg)
  2702. warningbox.setWindowTitle("Warning ...")
  2703. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2704. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2705. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2706. warningbox.exec_()
  2707. else:
  2708. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2709. min=-360, max=360, decimals=3)
  2710. num, ok = skewybox.get_value()
  2711. if ok:
  2712. # first get a bounding box to fit all
  2713. for obj in obj_list:
  2714. xmin, ymin, xmax, ymax = obj.bounds()
  2715. xminlist.append(xmin)
  2716. yminlist.append(ymin)
  2717. # get the minimum x,y and maximum x,y for all objects selected
  2718. xminimal = min(xminlist)
  2719. yminimal = min(yminlist)
  2720. for obj in obj_list:
  2721. obj.skew(0, num, point=(xminimal, yminimal))
  2722. obj.plot()
  2723. self.object_changed.emit(obj)
  2724. def delete_first_selected(self):
  2725. # Keep this for later
  2726. try:
  2727. name = self.collection.get_active().options["name"]
  2728. except AttributeError:
  2729. self.log.debug("Nothing selected for deletion")
  2730. return
  2731. # Remove plot
  2732. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  2733. # self.plotcanvas.auto_adjust_axes()
  2734. # Clear form
  2735. self.setup_component_editor()
  2736. # Remove from dictionary
  2737. self.collection.delete_active()
  2738. self.inform.emit("Object deleted: %s" % name)
  2739. def on_plots_updated(self):
  2740. """
  2741. Callback used to report when the plots have changed.
  2742. Adjust axes and zooms to fit.
  2743. :return: None
  2744. """
  2745. # self.plotcanvas.auto_adjust_axes()
  2746. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  2747. self.on_zoom_fit(None)
  2748. # TODO: Rework toolbar 'clear', 'replot' functions
  2749. def on_toolbar_replot(self):
  2750. """
  2751. Callback for toolbar button. Re-plots all objects.
  2752. :return: None
  2753. """
  2754. self.report_usage("on_toolbar_replot")
  2755. self.log.debug("on_toolbar_replot()")
  2756. try:
  2757. self.collection.get_active().read_form()
  2758. except AttributeError:
  2759. self.log.debug("on_toolbar_replot(): AttributeError")
  2760. pass
  2761. self.plot_all()
  2762. def on_row_activated(self, index):
  2763. if index.isValid():
  2764. if index.internalPointer().parent_item != self.collection.root_item:
  2765. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2766. def on_zoom_fit(self, event):
  2767. """
  2768. Callback for zoom-out request. This can be either from the corresponding
  2769. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  2770. with axes limits from the geometry bounds of all objects.
  2771. :param event: Ignored.
  2772. :return: None
  2773. """
  2774. self.plotcanvas.fit_view()
  2775. def grid_status(self):
  2776. if self.ui.grid_snap_btn.isChecked():
  2777. return 1
  2778. else:
  2779. return 0
  2780. def on_key_over_plot(self, event):
  2781. """
  2782. Callback for the key pressed event when the canvas is focused. Keyboard
  2783. shortcuts are handled here. So far, these are the shortcuts:
  2784. ========== ============================================
  2785. Key Action
  2786. ========== ============================================
  2787. '1' Zoom-fit. Fits the axes limits to the data.
  2788. '2' Zoom-out.
  2789. '3' Zoom-in.
  2790. 'ctrl+m' Toggle on-off the measuring tool.
  2791. ========== ============================================
  2792. :param event: Ignored.
  2793. :return: None
  2794. """
  2795. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  2796. if self.key_modifiers == QtCore.Qt.ControlModifier:
  2797. if event.key == 'A':
  2798. self.on_selectall()
  2799. if event.key == 'C':
  2800. self.on_copy_object()
  2801. if event.key == 'E':
  2802. self.on_fileopenexcellon()
  2803. if event.key == 'G':
  2804. self.on_fileopengerber()
  2805. if event.key == 'M':
  2806. self.measurement_tool.run()
  2807. if event.key == 'O':
  2808. self.on_file_openproject()
  2809. if event.key == 'S':
  2810. self.on_file_saveproject()
  2811. return
  2812. elif self.key_modifiers == QtCore.Qt.AltModifier:
  2813. # place holder for further shortcut key
  2814. return
  2815. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  2816. # place holder for further shortcut key
  2817. # Toggle axis
  2818. if event.key == 'G':
  2819. self.on_toggle_axis()
  2820. # Rotate Object by 90 degree CCW
  2821. if event.key == 'R':
  2822. self.on_rotate(silent=True, preset=-90)
  2823. # Toggle Workspace
  2824. if event.key == 'W':
  2825. self.on_workspace_menu()
  2826. return
  2827. else:
  2828. if event.key == self.defaults['fit_key']: # 1
  2829. self.on_zoom_fit(None)
  2830. return
  2831. if event.key == self.defaults['zoom_out_key']: # 2
  2832. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  2833. return
  2834. if event.key == self.defaults['zoom_in_key']: # 3
  2835. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  2836. return
  2837. if event.key == 'Delete':
  2838. self.on_delete()
  2839. return
  2840. if event.key == 'Space':
  2841. if self.collection.get_active() is not None:
  2842. self.collection.get_active().ui.plot_cb.toggle()
  2843. self.delete_selection_shape()
  2844. if event.key == 'C':
  2845. self.on_copy_name()
  2846. if event.key == 'E':
  2847. self.object2editor()
  2848. if event.key == self.defaults['grid_toggle_key']: # G
  2849. self.ui.grid_snap_btn.trigger()
  2850. if event.key == 'J':
  2851. self.on_jump_to()
  2852. if event.key == 'M':
  2853. self.move_tool.toggle()
  2854. return
  2855. if event.key == 'N':
  2856. self.on_new_geometry()
  2857. if event.key == 'Q':
  2858. if self.options["units"] == 'MM':
  2859. self.general_options_form.general_group.units_radio.set_value("IN")
  2860. else:
  2861. self.general_options_form.general_group.units_radio.set_value("MM")
  2862. self.on_toggle_units()
  2863. if event.key == 'R':
  2864. self.on_rotate(silent=True, preset=90)
  2865. if event.key == 'S':
  2866. self.on_toggle_shell()
  2867. if event.key == 'T':
  2868. self.transform_tool.run()
  2869. if event.key == 'V':
  2870. self.on_zoom_fit(None)
  2871. if event.key == 'X':
  2872. self.on_flipx()
  2873. if event.key == 'Y':
  2874. self.on_flipy()
  2875. if event.key == '`':
  2876. self.on_shortcut_list()
  2877. def on_key_release_over_plot(self, event):
  2878. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2879. if modifiers == QtCore.Qt.ControlModifier:
  2880. return
  2881. elif modifiers == QtCore.Qt.AltModifier:
  2882. # place holder for further shortcut key
  2883. return
  2884. elif modifiers == QtCore.Qt.ShiftModifier:
  2885. # place holder for further shortcut key
  2886. return
  2887. else:
  2888. return
  2889. def on_shortcut_list(self):
  2890. msg = '''<b>Shortcut list</b><br>
  2891. <br>
  2892. <b>~:</b> Show Shortcut List<br>
  2893. <br>
  2894. <b>1:</b> Zoom Fit<br>
  2895. <b>2:</b> Zoom Out<br>
  2896. <b>3:</b> Zoom In<br>
  2897. <b>A:</b> Draw an Arc (when in Edit Mode)<br>
  2898. <b>C:</b> Copy Obj_Name<br>
  2899. <b>C:</b> Copy Geo Item (when in Edit Mode)<br>
  2900. <b>E:</b> Edit Object (if selected)<br>
  2901. <b>G:</b> Grid On/Off<br>
  2902. <b>J:</b> Jump to Coordinates<br>
  2903. <b>M:</b> Move Obj<br>
  2904. <b>M:</b> Move Geo Item (when in Edit Mode)<br>
  2905. <b>N:</b> New Geometry<br>
  2906. <b>N:</b> Draw a Polygon (when in Edit Mode)<br>
  2907. <b>O:</b> Draw a Circle (when in Edit Mode)<br>
  2908. <b>Q:</b> Change Units<br>
  2909. <b>P:</b> Draw a Path (when in Edit Mode)<br>
  2910. <b>R:</b> Rotate by 90 degree CW<br>
  2911. <b>R:</b> Draw Rectangle (when in Edit Mode)<br>
  2912. <b>S:</b> Shell Toggle<br>
  2913. <b>T:</b> Transformation<br>
  2914. <b>V:</b> View Fit<br>
  2915. <b>X:</b> Flip on X_axis<br>
  2916. <b>Y:</b> Flip on Y_axis<br>
  2917. <br>
  2918. <b>Space:</b> En(Dis)able Obj Plot<br>
  2919. <b>CTRL+A:</b> Select All<br>
  2920. <b>CTRL+C:</b> Copy Obj<br>
  2921. <b>CTRL+E:</b> Open Excellon File<br>
  2922. <b>CTRL+G:</b> Open Gerber File<br>
  2923. <b>CTRL+M:</b> Measurement Tool<br>
  2924. <b>CTRL+O:</b> Open Project<br>
  2925. <b>CTRL+S:</b> Save Project As<br>
  2926. <b>CTRL+S:</b> Save Object and Exit Editor (when in Edit Mode)<br>
  2927. <br>
  2928. <b>SHIFT+G:</b> Toggle the axis<br>
  2929. <b>SHIFT+R:</b> Rotate by 90 degree CCW<br>
  2930. <b>SHIFT+W:</b> Toggle the workspace<br>
  2931. <b>Del:</b> Delete Obj'''
  2932. helpbox = QtWidgets.QMessageBox()
  2933. helpbox.setText(msg)
  2934. helpbox.setWindowTitle("Help")
  2935. helpbox.setWindowIcon(QtGui.QIcon('share/help.png'))
  2936. helpbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2937. helpbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2938. helpbox.exec_()
  2939. def on_copy_name(self):
  2940. obj = self.collection.get_active()
  2941. name = obj.options["name"]
  2942. self.clipboard.setText(name)
  2943. self.inform.emit("Name copied on clipboard ...")
  2944. def on_mouse_click_over_plot(self, event):
  2945. """
  2946. Callback for the mouse click event over the plot. This event is generated
  2947. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2948. For details, see: http://matplotlib.org/users/event_handling.html
  2949. Default actions are:
  2950. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  2951. :param event: Contains information about the event, like which button
  2952. was clicked, the pixel coordinates and the axes coordinates.
  2953. :return: None
  2954. """
  2955. self.pos = []
  2956. # So it can receive key presses
  2957. self.plotcanvas.vispy_canvas.native.setFocus()
  2958. # Set the mouse button for panning
  2959. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  2960. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2961. if self.grid_status() == True:
  2962. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  2963. self.app_cursor.enabled = True
  2964. else:
  2965. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  2966. self.app_cursor.enabled = False
  2967. try:
  2968. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  2969. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  2970. modifiers = QtWidgets.QApplication.keyboardModifiers()
  2971. if event.button == 1:
  2972. # Reset here the relative coordinates so there is a new reference on the click position
  2973. if self.rel_point1 is None:
  2974. self.rel_point1 = self.pos
  2975. else:
  2976. self.rel_point2 = copy(self.rel_point1)
  2977. self.rel_point1 = self.pos
  2978. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  2979. if modifiers == QtCore.Qt.ShiftModifier:
  2980. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  2981. return
  2982. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  2983. # and if it's not selected then it will be selected
  2984. if modifiers == QtCore.Qt.ControlModifier:
  2985. # If there is no active command (self.command_active is None) then we check if we clicked on
  2986. # a object by checking the bounding limits against mouse click position
  2987. if self.command_active is None:
  2988. self.select_objects(key='CTRL')
  2989. else:
  2990. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  2991. # checking the bounding limits against mouse click position
  2992. if self.command_active is None:
  2993. self.select_objects()
  2994. self.on_mouse_move_over_plot(event, origin_click=True)
  2995. except Exception as e:
  2996. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  2997. def on_double_click_over_plot(self, event):
  2998. # make double click work only for the LMB
  2999. if event.button == 1:
  3000. if not self.collection.get_selected():
  3001. pass
  3002. else:
  3003. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3004. #delete the selection shape(S) as it may be in the way
  3005. self.delete_selection_shape()
  3006. def on_mouse_move_over_plot(self, event, origin_click=None):
  3007. """
  3008. Callback for the mouse motion event over the plot. This event is generated
  3009. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3010. For details, see: http://matplotlib.org/users/event_handling.html
  3011. :param event: Contains information about the event.
  3012. :param origin_click
  3013. :return: None
  3014. """
  3015. # So it can receive key presses
  3016. self.plotcanvas.vispy_canvas.native.setFocus()
  3017. self.pos_jump = event.pos
  3018. if origin_click is True:
  3019. pass
  3020. else:
  3021. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3022. if event.button == 2:
  3023. self.panning_action = True
  3024. return
  3025. else:
  3026. self.panning_action = False
  3027. if self.rel_point1 is not None:
  3028. try: # May fail in case mouse not within axes
  3029. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3030. if self.grid_status():
  3031. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3032. self.app_cursor.enabled = True
  3033. # Update cursor
  3034. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3035. else:
  3036. pos = (pos_canvas[0], pos_canvas[1])
  3037. self.app_cursor.enabled = False
  3038. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3039. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3040. dx = pos[0] - self.rel_point1[0]
  3041. dy = pos[1] - self.rel_point1[1]
  3042. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3043. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3044. self.mouse = [pos[0], pos[1]]
  3045. # if the mouse is moved and the LMB is clicked then the action is a selection
  3046. if event.is_dragging == 1 and event.button == 1:
  3047. self.delete_selection_shape()
  3048. if dx < 0:
  3049. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3050. face_color=self.defaults['global_alt_sel_fill'])
  3051. self.selection_type = False
  3052. else:
  3053. self.draw_moving_selection_shape(self.pos, pos)
  3054. self.selection_type = True
  3055. # delete the status message on mouse move
  3056. # self.inform.emit("")
  3057. except:
  3058. self.ui.position_label.setText("")
  3059. self.ui.rel_position_label.setText("")
  3060. self.mouse = None
  3061. def on_mouse_click_release_over_plot(self, event):
  3062. """
  3063. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3064. and has been registered in ''self.__init__()''.
  3065. :param event: contains information about the event.
  3066. :return:
  3067. """
  3068. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3069. if self.grid_status():
  3070. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3071. else:
  3072. pos = (pos_canvas[0], pos_canvas[1])
  3073. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3074. # canvas menu
  3075. try:
  3076. if event.button == 2: # right click
  3077. if self.panning_action is True:
  3078. self.panning_action = False
  3079. else:
  3080. self.cursor = QtGui.QCursor()
  3081. self.ui.popMenu.popup(self.cursor.pos())
  3082. except Exception as e:
  3083. log.warning("Error: %s" % str(e))
  3084. return
  3085. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3086. # selection and then select a type of selection ("enclosing" or "touching")
  3087. try:
  3088. if event.button == 1: # left click
  3089. if self.selection_type is not None:
  3090. self.selection_area_handler(self.pos, pos, self.selection_type)
  3091. self.selection_type = None
  3092. except Exception as e:
  3093. log.warning("Error: %s" % str(e))
  3094. return
  3095. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3096. """
  3097. :param start_pos: mouse position when the selection LMB click was done
  3098. :param end_pos: mouse position when the left mouse button is released
  3099. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3100. :return:
  3101. """
  3102. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3103. self.delete_selection_shape()
  3104. for obj in self.collection.get_list():
  3105. try:
  3106. # select the object(s) only if it is enabled (plotted)
  3107. if obj.options['plot']:
  3108. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3109. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3110. if sel_type is True:
  3111. if poly_obj.within(poly_selection):
  3112. # create the selection box around the selected object
  3113. self.draw_selection_shape(obj)
  3114. self.collection.set_active(obj.options['name'])
  3115. else:
  3116. if poly_selection.intersects(poly_obj):
  3117. # create the selection box around the selected object
  3118. self.draw_selection_shape(obj)
  3119. self.collection.set_active(obj.options['name'])
  3120. except:
  3121. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3122. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3123. # In this case poly_obj creation (see above) will fail
  3124. pass
  3125. def select_objects(self, key=None):
  3126. # list where we store the overlapped objects under our mouse left click position
  3127. objects_under_the_click_list = []
  3128. # Populate the list with the overlapped objects on the click position
  3129. curr_x, curr_y = self.pos
  3130. for obj in self.all_objects_list:
  3131. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3132. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3133. if obj.options['name'] not in objects_under_the_click_list:
  3134. if obj.options['plot']:
  3135. # add objects to the objects_under_the_click list only if the object is plotted
  3136. # (active and not disabled)
  3137. objects_under_the_click_list.append(obj.options['name'])
  3138. try:
  3139. # If there is no element in the overlapped objects list then make everyone inactive
  3140. # because we selected "nothing"
  3141. if not objects_under_the_click_list:
  3142. self.collection.set_all_inactive()
  3143. # delete the possible selection box around a possible selected object
  3144. self.delete_selection_shape()
  3145. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3146. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3147. else:
  3148. # case when there is only an object under the click and we toggle it
  3149. if len(objects_under_the_click_list) == 1:
  3150. if self.collection.get_active() is None :
  3151. self.collection.set_active(objects_under_the_click_list[0])
  3152. # create the selection box around the selected object
  3153. curr_sel_obj = self.collection.get_active()
  3154. self.draw_selection_shape(curr_sel_obj)
  3155. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3156. self.collection.set_all_inactive()
  3157. self.delete_selection_shape()
  3158. self.collection.set_active(objects_under_the_click_list[0])
  3159. # create the selection box around the selected object
  3160. curr_sel_obj = self.collection.get_active()
  3161. self.draw_selection_shape(curr_sel_obj)
  3162. else:
  3163. self.collection.set_all_inactive()
  3164. self.delete_selection_shape()
  3165. else:
  3166. # If there is no selected object
  3167. # make active the first element of the overlapped objects list
  3168. if self.collection.get_active() is None:
  3169. self.collection.set_active(objects_under_the_click_list[0])
  3170. name_sel_obj = self.collection.get_active().options['name']
  3171. # In case that there is a selected object but it is not in the overlapped object list
  3172. # make that object inactive and activate the first element in the overlapped object list
  3173. if name_sel_obj not in objects_under_the_click_list:
  3174. self.collection.set_inactive(name_sel_obj)
  3175. name_sel_obj = objects_under_the_click_list[0]
  3176. self.collection.set_active(name_sel_obj)
  3177. else:
  3178. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3179. self.collection.set_all_inactive()
  3180. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3181. curr_sel_obj = self.collection.get_active()
  3182. # delete the possible selection box around a possible selected object
  3183. self.delete_selection_shape()
  3184. # create the selection box around the selected object
  3185. self.draw_selection_shape(curr_sel_obj)
  3186. # for obj in self.collection.get_list():
  3187. # obj.plot()
  3188. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3189. # TODO: on selected objects change the object colors and do not draw the selection box
  3190. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3191. except Exception as e:
  3192. log.error("[error] Something went bad. %s" % str(e))
  3193. return
  3194. def delete_selection_shape(self):
  3195. self.move_tool.sel_shapes.clear()
  3196. self.move_tool.sel_shapes.redraw()
  3197. def draw_selection_shape(self, sel_obj):
  3198. """
  3199. :param sel_obj: the object for which the selection shape must be drawn
  3200. :return:
  3201. """
  3202. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3203. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3204. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3205. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3206. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3207. #blue_t = Color('blue')
  3208. blue_t = Color(self.defaults['global_sel_fill'])
  3209. blue_t.alpha = 0.3
  3210. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3211. face_color=blue_t, update=True, layer=0, tolerance=None))
  3212. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3213. """
  3214. :param old_coords: old coordinates
  3215. :param coords: new coordinates
  3216. :return:
  3217. """
  3218. if 'color' in kwargs:
  3219. color = kwargs['color']
  3220. else:
  3221. color = self.defaults['global_sel_line']
  3222. if 'face_color' in kwargs:
  3223. face_color = kwargs['face_color']
  3224. else:
  3225. face_color = self.defaults['global_sel_fill']
  3226. x0, y0 = old_coords
  3227. x1, y1 = coords
  3228. pt1 = (x0, y0)
  3229. pt2 = (x1, y0)
  3230. pt3 = (x1, y1)
  3231. pt4 = (x0, y1)
  3232. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3233. color_t = Color(face_color)
  3234. color_t.alpha = 0.3
  3235. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3236. layer=0, tolerance=None)
  3237. def on_file_new(self):
  3238. """
  3239. Callback for menu item File->New. Returns the application to its
  3240. startup state. This method is thread-safe.
  3241. :return: None
  3242. """
  3243. self.report_usage("on_file_new")
  3244. # Remove everything from memory
  3245. App.log.debug("on_file_new()")
  3246. # Clear pool
  3247. self.clear_pool()
  3248. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3249. self.init_tcl()
  3250. self.delete_selection_shape()
  3251. self.collection.delete_all()
  3252. self.setup_component_editor()
  3253. # Clear project filename
  3254. self.project_filename = None
  3255. # Load the application defaults
  3256. self.load_defaults()
  3257. # Re-fresh project options
  3258. self.on_options_app2project()
  3259. # Init Tools
  3260. self.init_tools()
  3261. # take the focus of the Notebook on Project Tab.
  3262. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3263. def obj_properties(self):
  3264. self.properties_tool.run()
  3265. def on_fileopengerber(self):
  3266. """
  3267. File menu callback for opening a Gerber.
  3268. :return: None
  3269. """
  3270. self.report_usage("on_fileopengerber")
  3271. App.log.debug("on_fileopengerber()")
  3272. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3273. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3274. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3275. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3276. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3277. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3278. "Allegro Files (*.art);;" \
  3279. "Mentor Files (*.pho *.gdo);;" \
  3280. "All Files (*.*)"
  3281. try:
  3282. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber",
  3283. directory=self.get_last_folder(), filter=_filter_)
  3284. except TypeError:
  3285. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber", filter=_filter_)
  3286. # The Qt methods above will return a QString which can cause problems later.
  3287. # So far json.dump() will fail to serialize it.
  3288. # TODO: Improve the serialization methods and remove this fix.
  3289. filename = str(filename)
  3290. if filename == "":
  3291. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3292. else:
  3293. self.worker_task.emit({'fcn': self.open_gerber,
  3294. 'params': [filename]})
  3295. def on_fileopengerber_follow(self):
  3296. """
  3297. File menu callback for opening a Gerber.
  3298. :return: None
  3299. """
  3300. self.report_usage("on_fileopengerber_follow")
  3301. App.log.debug("on_fileopengerber_follow()")
  3302. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3303. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3304. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3305. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3306. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3307. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3308. "Allegro Files (*.art);;" \
  3309. "Mentor Files (*.pho *.gdo);;" \
  3310. "All Files (*.*)"
  3311. try:
  3312. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3313. directory=self.get_last_folder(), filter=_filter_)
  3314. except TypeError:
  3315. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3316. # The Qt methods above will return a QString which can cause problems later.
  3317. # So far json.dump() will fail to serialize it.
  3318. # TODO: Improve the serialization methods and remove this fix.
  3319. filename = str(filename)
  3320. follow = True
  3321. if filename == "":
  3322. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3323. else:
  3324. self.worker_task.emit({'fcn': self.open_gerber,
  3325. 'params': [filename, follow]})
  3326. def on_fileopenexcellon(self):
  3327. """
  3328. File menu callback for opening an Excellon file.
  3329. :return: None
  3330. """
  3331. self.report_usage("on_fileopenexcellon")
  3332. App.log.debug("on_fileopenexcellon()")
  3333. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3334. "All Files (*.*)"
  3335. try:
  3336. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Excellon",
  3337. directory=self.get_last_folder(), filter=_filter_)
  3338. except TypeError:
  3339. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Excellon", filter=_filter_)
  3340. # The Qt methods above will return a QString which can cause problems later.
  3341. # So far json.dump() will fail to serialize it.
  3342. # TODO: Improve the serialization methods and remove this fix.
  3343. filename = str(filename)
  3344. if filename == "":
  3345. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3346. else:
  3347. self.worker_task.emit({'fcn': self.open_excellon,
  3348. 'params': [filename]})
  3349. def on_fileopengcode(self):
  3350. """
  3351. File menu call back for opening gcode.
  3352. :return: None
  3353. """
  3354. self.report_usage("on_fileopengcode")
  3355. App.log.debug("on_fileopengcode()")
  3356. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3357. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3358. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3359. "All Files (*.*)"
  3360. try:
  3361. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open G-Code",
  3362. directory=self.get_last_folder(), filter=_filter_)
  3363. except TypeError:
  3364. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open G-Code", filter=_filter_)
  3365. # The Qt methods above will return a QString which can cause problems later.
  3366. # So far json.dump() will fail to serialize it.
  3367. # TODO: Improve the serialization methods and remove this fix.
  3368. filename = str(filename)
  3369. if filename == "":
  3370. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3371. else:
  3372. self.worker_task.emit({'fcn': self.open_gcode,
  3373. 'params': [filename]})
  3374. def on_file_openproject(self):
  3375. """
  3376. File menu callback for opening a project.
  3377. :return: None
  3378. """
  3379. self.report_usage("on_file_openproject")
  3380. App.log.debug("on_file_openproject()")
  3381. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3382. try:
  3383. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3384. directory=self.get_last_folder(), filter=_filter_)
  3385. except TypeError:
  3386. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3387. # The Qt methods above will return a QString which can cause problems later.
  3388. # So far json.dump() will fail to serialize it.
  3389. # TODO: Improve the serialization methods and remove this fix.
  3390. filename = str(filename)
  3391. if filename == "":
  3392. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3393. else:
  3394. # self.worker_task.emit({'fcn': self.open_project,
  3395. # 'params': [filename]})
  3396. # The above was failing because open_project() is not
  3397. # thread safe. The new_project()
  3398. self.open_project(filename)
  3399. def on_file_exportsvg(self):
  3400. """
  3401. Callback for menu item File->Export SVG.
  3402. :return: None
  3403. """
  3404. self.report_usage("on_file_exportsvg")
  3405. App.log.debug("on_file_exportsvg()")
  3406. obj = self.collection.get_active()
  3407. if obj is None:
  3408. self.inform.emit("WARNING: No object selected.")
  3409. msg = "Please Select a Geometry object to export"
  3410. msgbox = QtWidgets.QMessageBox()
  3411. msgbox.setInformativeText(msg)
  3412. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3413. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3414. msgbox.exec_()
  3415. return
  3416. # Check for more compatible types and add as required
  3417. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3418. and not isinstance(obj, FlatCAMExcellon)):
  3419. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3420. msgbox = QtWidgets.QMessageBox()
  3421. msgbox.setInformativeText(msg)
  3422. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3423. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3424. msgbox.exec_()
  3425. return
  3426. name = self.collection.get_active().options["name"]
  3427. filter = "SVG File (*.svg);;All Files (*.*)"
  3428. try:
  3429. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3430. directory=self.get_last_save_folder(), filter=filter)
  3431. except TypeError:
  3432. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3433. filename = str(filename)
  3434. if filename == "":
  3435. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3436. return
  3437. else:
  3438. self.export_svg(name, filename)
  3439. self.file_saved.emit("SVG", filename)
  3440. def on_file_exportpng(self):
  3441. self.report_usage("on_file_exportpng")
  3442. App.log.debug("on_file_exportpng()")
  3443. image = _screenshot()
  3444. data = np.asarray(image)
  3445. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3446. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3447. return
  3448. filter = "PNG File (*.png);;All Files (*.*)"
  3449. try:
  3450. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3451. directory=self.get_last_save_folder(), filter=filter)
  3452. except TypeError:
  3453. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3454. filename = str(filename)
  3455. if filename == "":
  3456. self.inform.emit("Export PNG cancelled.")
  3457. return
  3458. else:
  3459. write_png(filename, data)
  3460. self.file_saved.emit("png", filename)
  3461. def on_file_exportexcellon(self, altium_format=None):
  3462. """
  3463. Callback for menu item File->Export SVG.
  3464. :return: None
  3465. """
  3466. self.report_usage("on_file_exportexcellon")
  3467. App.log.debug("on_file_exportexcellon()")
  3468. obj = self.collection.get_active()
  3469. if obj is None:
  3470. self.inform.emit("[warning_notcl] No object selected.")
  3471. msg = "Please Select an Excellon object to export"
  3472. msgbox = QtWidgets.QMessageBox()
  3473. msgbox.setInformativeText(msg)
  3474. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3475. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3476. msgbox.exec_()
  3477. return
  3478. # Check for more compatible types and add as required
  3479. if not isinstance(obj, FlatCAMExcellon):
  3480. msg = "[warning_notcl] Only Excellon objects can be used."
  3481. msgbox = QtWidgets.QMessageBox()
  3482. msgbox.setInformativeText(msg)
  3483. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3484. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3485. msgbox.exec_()
  3486. return
  3487. name = self.collection.get_active().options["name"]
  3488. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3489. try:
  3490. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3491. directory=self.get_last_save_folder(), filter=filter)
  3492. except TypeError:
  3493. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3494. filename = str(filename)
  3495. if filename == "":
  3496. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3497. return
  3498. else:
  3499. if altium_format == None:
  3500. self.export_excellon(name, filename)
  3501. self.file_saved.emit("Excellon", filename)
  3502. else:
  3503. self.export_excellon(name, filename, altium_format=True)
  3504. self.file_saved.emit("Excellon", filename)
  3505. def on_file_exportdxf(self):
  3506. """
  3507. Callback for menu item File->Export DXF.
  3508. :return: None
  3509. """
  3510. self.report_usage("on_file_exportdxf")
  3511. App.log.debug("on_file_exportdxf()")
  3512. obj = self.collection.get_active()
  3513. if obj is None:
  3514. self.inform.emit("W[warning_notcl] No object selected.")
  3515. msg = "Please Select a Geometry object to export"
  3516. msgbox = QtWidgets.QMessageBox()
  3517. msgbox.setInformativeText(msg)
  3518. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3519. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3520. msgbox.exec_()
  3521. return
  3522. # Check for more compatible types and add as required
  3523. if not isinstance(obj, FlatCAMGeometry):
  3524. msg = "[error_notcl] Only Geometry objects can be used."
  3525. msgbox = QtWidgets.QMessageBox()
  3526. msgbox.setInformativeText(msg)
  3527. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3528. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3529. msgbox.exec_()
  3530. return
  3531. name = self.collection.get_active().options["name"]
  3532. filter = "DXF File (*.DXF);;All Files (*.*)"
  3533. try:
  3534. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3535. directory=self.get_last_save_folder(), filter=filter)
  3536. except TypeError:
  3537. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3538. filename = str(filename)
  3539. if filename == "":
  3540. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3541. return
  3542. else:
  3543. self.export_dxf(name, filename)
  3544. self.file_saved.emit("DXF", filename)
  3545. def on_file_importsvg(self, type_of_obj):
  3546. """
  3547. Callback for menu item File->Import SVG.
  3548. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3549. :type type_of_obj: str
  3550. :return: None
  3551. """
  3552. self.report_usage("on_file_importsvg")
  3553. App.log.debug("on_file_importsvg()")
  3554. filter = "SVG File (*.svg);;All Files (*.*)"
  3555. try:
  3556. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import SVG",
  3557. directory=self.get_last_folder(), filter=filter)
  3558. except TypeError:
  3559. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import SVG", filter=filter)
  3560. filename = str(filename)
  3561. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3562. type_of_obj = "geometry"
  3563. if filename == "":
  3564. self.inform.emit("[warning_notcl]Open cancelled.")
  3565. else:
  3566. self.worker_task.emit({'fcn': self.import_svg,
  3567. 'params': [filename, type_of_obj]})
  3568. # self.import_svg(filename, "geometry")
  3569. def on_file_importdxf(self, type_of_obj):
  3570. """
  3571. Callback for menu item File->Import DXF.
  3572. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3573. :type type_of_obj: str
  3574. :return: None
  3575. """
  3576. self.report_usage("on_file_importdxf")
  3577. App.log.debug("on_file_importdxf()")
  3578. filter = "DXF File (*.DXF);;All Files (*.*)"
  3579. try:
  3580. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import DXF",
  3581. directory=self.get_last_folder(), filter=filter)
  3582. except TypeError:
  3583. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import DXF", filter=filter)
  3584. filename = str(filename)
  3585. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3586. type_of_obj = "geometry"
  3587. if filename == "":
  3588. self.inform.emit("[warning_notcl]Open cancelled.")
  3589. else:
  3590. self.worker_task.emit({'fcn': self.import_dxf,
  3591. 'params': [filename, type_of_obj]})
  3592. def on_filerunscript(self):
  3593. """
  3594. File menu callback for loading and running a TCL script.
  3595. :return: None
  3596. """
  3597. self.report_usage("on_filerunscript")
  3598. App.log.debug("on_file_runscript()")
  3599. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3600. try:
  3601. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3602. directory=self.get_last_folder(), filter=_filter_)
  3603. except TypeError:
  3604. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3605. # The Qt methods above will return a QString which can cause problems later.
  3606. # So far json.dump() will fail to serialize it.
  3607. # TODO: Improve the serialization methods and remove this fix.
  3608. filename = str(filename)
  3609. if filename == "":
  3610. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3611. else:
  3612. try:
  3613. with open(filename, "r") as tcl_script:
  3614. cmd_line_shellfile_content = tcl_script.read()
  3615. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3616. except Exception as ext:
  3617. print("ERROR: ", ext)
  3618. sys.exit(2)
  3619. def on_file_saveproject(self):
  3620. """
  3621. Callback for menu item File->Save Project. Saves the project to
  3622. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  3623. if set to None. The project is saved by calling ``self.save_project()``.
  3624. :return: None
  3625. """
  3626. self.report_usage("on_file_saveproject")
  3627. if self.project_filename is None:
  3628. self.on_file_saveprojectas()
  3629. else:
  3630. self.worker_task.emit({'fcn': self.save_project,
  3631. 'params': [self.project_filename]})
  3632. # self.save_project(self.project_filename)
  3633. self.file_opened.emit("project", self.project_filename)
  3634. self.file_saved.emit("project", self.project_filename)
  3635. def on_file_saveprojectas(self, make_copy=False):
  3636. """
  3637. Callback for menu item File->Save Project As... Opens a file
  3638. chooser and saves the project to the given file via
  3639. ``self.save_project()``.
  3640. :return: None
  3641. """
  3642. self.report_usage("on_file_saveprojectas")
  3643. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  3644. try:
  3645. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  3646. directory=self.get_last_save_folder(), filter=filter)
  3647. except TypeError:
  3648. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  3649. filename = str(filename)
  3650. if filename == '':
  3651. self.inform.emit("[warning_notcl]Save Project cancelled.")
  3652. return
  3653. try:
  3654. f = open(filename, 'r')
  3655. f.close()
  3656. exists = True
  3657. except IOError:
  3658. exists = False
  3659. msg = "File exists. Overwrite?"
  3660. if exists:
  3661. msgbox = QtWidgets.QMessageBox()
  3662. msgbox.setInformativeText(msg)
  3663. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  3664. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  3665. result = msgbox.exec_()
  3666. if result ==QtWidgets.QMessageBox.Cancel:
  3667. return
  3668. self.worker_task.emit({'fcn': self.save_project,
  3669. 'params': [filename]})
  3670. # self.save_project(filename)
  3671. self.file_opened.emit("project", filename)
  3672. self.file_saved.emit("project", filename)
  3673. if not make_copy:
  3674. self.project_filename = filename
  3675. def export_svg(self, obj_name, filename, scale_factor=0.00):
  3676. """
  3677. Exports a Geometry Object to an SVG file.
  3678. :param filename: Path to the SVG file to save to.
  3679. :return:
  3680. """
  3681. if filename is None:
  3682. filename = self.defaults["global_last_save_folder"]
  3683. self.log.debug("export_svg()")
  3684. try:
  3685. obj = self.collection.get_by_name(str(obj_name))
  3686. except:
  3687. # TODO: The return behavior has not been established... should raise exception?
  3688. return "Could not retrieve object: %s" % obj_name
  3689. with self.proc_container.new("Exporting SVG") as proc:
  3690. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3691. # Determine bounding area for svg export
  3692. bounds = obj.bounds()
  3693. size = obj.size()
  3694. # Convert everything to strings for use in the xml doc
  3695. svgwidth = str(size[0])
  3696. svgheight = str(size[1])
  3697. minx = str(bounds[0])
  3698. miny = str(bounds[1] - size[1])
  3699. uom = obj.units.lower()
  3700. # Add a SVG Header and footer to the svg output from shapely
  3701. # The transform flips the Y Axis so that everything renders
  3702. # properly within svg apps such as inkscape
  3703. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  3704. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  3705. svg_header += 'width="' + svgwidth + uom + '" '
  3706. svg_header += 'height="' + svgheight + uom + '" '
  3707. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  3708. svg_header += '<g transform="scale(1,-1)">'
  3709. svg_footer = '</g> </svg>'
  3710. svg_elem = svg_header + exported_svg + svg_footer
  3711. # Parse the xml through a xml parser just to add line feeds
  3712. # and to make it look more pretty for the output
  3713. svgcode = parse_xml_string(svg_elem)
  3714. with open(filename, 'w') as fp:
  3715. fp.write(svgcode.toprettyxml())
  3716. self.file_saved.emit("SVG", filename)
  3717. self.inform.emit("[success] SVG file exported to " + filename)
  3718. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  3719. """
  3720. Exports a Geometry Object to an SVG file in negative.
  3721. :param filename: Path to the SVG file to save to.
  3722. :param: use_thread: If True use threads
  3723. :type: Bool
  3724. :return:
  3725. """
  3726. if filename is None:
  3727. filename = self.defaults["global_last_save_folder"]
  3728. self.log.debug("export_svg() negative")
  3729. try:
  3730. obj = self.collection.get_by_name(str(obj_name))
  3731. except:
  3732. # TODO: The return behavior has not been established... should raise exception?
  3733. return "Could not retrieve object: %s" % obj_name
  3734. try:
  3735. box = self.collection.get_by_name(str(box_name))
  3736. except:
  3737. # TODO: The return behavior has not been established... should raise exception?
  3738. return "Could not retrieve object: %s" % box_name
  3739. if box is None:
  3740. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  3741. box = obj
  3742. def make_negative_film():
  3743. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3744. self.progress.emit(40)
  3745. # Determine bounding area for svg export
  3746. bounds = box.bounds()
  3747. size = box.size()
  3748. uom = obj.units.lower()
  3749. # Convert everything to strings for use in the xml doc
  3750. svgwidth = str(size[0] + (2 * boundary))
  3751. svgheight = str(size[1] + (2 * boundary))
  3752. minx = str(bounds[0] - boundary)
  3753. miny = str(bounds[1] + boundary + size[1])
  3754. miny_rect = str(bounds[1] - boundary)
  3755. # Add a SVG Header and footer to the svg output from shapely
  3756. # The transform flips the Y Axis so that everything renders
  3757. # properly within svg apps such as inkscape
  3758. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  3759. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  3760. svg_header += 'width="' + svgwidth + uom + '" '
  3761. svg_header += 'height="' + svgheight + uom + '" '
  3762. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  3763. svg_header += '>'
  3764. svg_header += '<g transform="scale(1,-1)">'
  3765. svg_footer = '</g> </svg>'
  3766. self.progress.emit(60)
  3767. # Change the attributes of the exported SVG
  3768. # We don't need stroke-width - wrong, we do when we have lines with certain width
  3769. # We set opacity to maximum
  3770. # We set the color to WHITE
  3771. root = ET.fromstring(exported_svg)
  3772. for child in root:
  3773. child.set('fill', '#FFFFFF')
  3774. child.set('opacity', '1.0')
  3775. child.set('stroke', '#FFFFFF')
  3776. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  3777. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  3778. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  3779. first_svg_elem_tag = 'rect'
  3780. first_svg_elem_attribs = {
  3781. 'x': minx,
  3782. 'y': miny_rect,
  3783. 'width': svgwidth,
  3784. 'height': svgheight,
  3785. 'id': 'neg_rect',
  3786. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  3787. }
  3788. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  3789. exported_svg = ET.tostring(root)
  3790. svg_elem = svg_header + str(exported_svg) + svg_footer
  3791. self.progress.emit(80)
  3792. # Parse the xml through a xml parser just to add line feeds
  3793. # and to make it look more pretty for the output
  3794. doc = parse_xml_string(svg_elem)
  3795. with open(filename, 'w') as fp:
  3796. fp.write(doc.toprettyxml())
  3797. self.progress.emit(100)
  3798. self.file_saved.emit("SVG", filename)
  3799. self.inform.emit("[success] SVG file exported to " + filename)
  3800. if use_thread is True:
  3801. proc = self.proc_container.new("Generating Film ... Please wait.")
  3802. def job_thread_film(app_obj):
  3803. try:
  3804. make_negative_film()
  3805. except Exception as e:
  3806. proc.done()
  3807. return
  3808. proc.done()
  3809. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  3810. else:
  3811. make_negative_film()
  3812. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  3813. """
  3814. Exports a Geometry Object to an SVG file in negative.
  3815. :param filename: Path to the SVG file to save to.
  3816. :param: use_thread: If True use threads
  3817. :type: Bool
  3818. :return:
  3819. """
  3820. if filename is None:
  3821. filename = self.defaults["global_last_save_folder"]
  3822. self.log.debug("export_svg() black")
  3823. try:
  3824. obj = self.collection.get_by_name(str(obj_name))
  3825. except:
  3826. # TODO: The return behavior has not been established... should raise exception?
  3827. return "Could not retrieve object: %s" % obj_name
  3828. try:
  3829. box = self.collection.get_by_name(str(box_name))
  3830. except:
  3831. # TODO: The return behavior has not been established... should raise exception?
  3832. return "Could not retrieve object: %s" % box_name
  3833. if box is None:
  3834. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  3835. box = obj
  3836. def make_black_film():
  3837. exported_svg = obj.export_svg(scale_factor=scale_factor)
  3838. self.progress.emit(40)
  3839. # Change the attributes of the exported SVG
  3840. # We don't need stroke-width
  3841. # We set opacity to maximum
  3842. # We set the colour to WHITE
  3843. root = ET.fromstring(exported_svg)
  3844. for child in root:
  3845. child.set('fill', '#000000')
  3846. child.set('opacity', '1.0')
  3847. child.set('stroke', '#000000')
  3848. exported_svg = ET.tostring(root)
  3849. # Determine bounding area for svg export
  3850. bounds = box.bounds()
  3851. size = box.size()
  3852. # This contain the measure units
  3853. uom = obj.units.lower()
  3854. # Define a boundary around SVG of about 1.0mm (~39mils)
  3855. if uom in "mm":
  3856. boundary = 1.0
  3857. else:
  3858. boundary = 0.0393701
  3859. self.progress.emit(80)
  3860. # Convert everything to strings for use in the xml doc
  3861. svgwidth = str(size[0] + (2 * boundary))
  3862. svgheight = str(size[1] + (2 * boundary))
  3863. minx = str(bounds[0] - boundary)
  3864. miny = str(bounds[1] + boundary + size[1])
  3865. self.log.debug(minx)
  3866. self.log.debug(miny)
  3867. # Add a SVG Header and footer to the svg output from shapely
  3868. # The transform flips the Y Axis so that everything renders
  3869. # properly within svg apps such as inkscape
  3870. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  3871. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  3872. svg_header += 'width="' + svgwidth + uom + '" '
  3873. svg_header += 'height="' + svgheight + uom + '" '
  3874. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  3875. svg_header += '>'
  3876. svg_header += '<g transform="scale(1,-1)">'
  3877. svg_footer = '</g> </svg>'
  3878. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  3879. self.progress.emit(90)
  3880. # Parse the xml through a xml parser just to add line feeds
  3881. # and to make it look more pretty for the output
  3882. doc = parse_xml_string(svg_elem)
  3883. with open(filename, 'w') as fp:
  3884. fp.write(doc.toprettyxml())
  3885. self.progress.emit(100)
  3886. self.file_saved.emit("SVG", filename)
  3887. self.inform.emit("[success] SVG file exported to " + filename)
  3888. if use_thread is True:
  3889. proc = self.proc_container.new("Generating Film ... Please wait.")
  3890. def job_thread_film(app_obj):
  3891. try:
  3892. make_black_film()
  3893. except Exception as e:
  3894. proc.done()
  3895. return
  3896. proc.done()
  3897. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  3898. else:
  3899. make_black_film()
  3900. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  3901. """
  3902. Exports a Geometry Object to an Excellon file.
  3903. :param filename: Path to the Excellon file to save to.
  3904. :return:
  3905. """
  3906. if filename is None:
  3907. filename = self.defaults["global_last_save_folder"]
  3908. self.log.debug("export_excellon()")
  3909. format_exc = ';FILE_FORMAT=2:4\n'
  3910. units = ''
  3911. try:
  3912. obj = self.collection.get_by_name(str(obj_name))
  3913. except:
  3914. # TODO: The return behavior has not been established... should raise exception?
  3915. return "Could not retrieve object: %s" % obj_name
  3916. # updated units
  3917. units = self.general_options_form.general_group.units_radio.get_value().upper()
  3918. if units == 'IN' or units == 'INCH':
  3919. units = 'INCH'
  3920. elif units == 'MM' or units == 'METRIC':
  3921. units ='METRIC'
  3922. def make_excellon():
  3923. try:
  3924. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  3925. header = 'M48\n'
  3926. header += ';EXCELLON GENERATED BY FLATCAM - www.flatcam.org 2018\n'
  3927. header += ';Filename: %s' % str(obj_name) + '\n'
  3928. header += ';Created on : %s' % time_str + '\n'
  3929. if altium_format == None:
  3930. has_slots, excellon_code = obj.export_excellon()
  3931. header += units + '\n'
  3932. for tool in obj.tools:
  3933. if units == 'METRIC':
  3934. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  3935. else:
  3936. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  3937. else:
  3938. has_slots, excellon_code = obj.export_excellon_altium()
  3939. header += 'INCH,LZ\n'
  3940. header += format_exc
  3941. for tool in obj.tools:
  3942. if units == 'METRIC':
  3943. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  3944. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  3945. else:
  3946. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  3947. header += '%\n'
  3948. footer = 'M30\n'
  3949. exported_excellon = header
  3950. exported_excellon += excellon_code
  3951. exported_excellon += footer
  3952. with open(filename, 'w') as fp:
  3953. fp.write(exported_excellon)
  3954. self.file_saved.emit("Excellon", filename)
  3955. self.inform.emit("[success] Excellon file exported to " + filename)
  3956. except:
  3957. return 'fail'
  3958. if use_thread is True:
  3959. with self.proc_container.new("Exporting Excellon") as proc:
  3960. def job_thread_exc(app_obj):
  3961. ret = make_excellon()
  3962. if ret == 'fail':
  3963. self.inform.emit('[error_notcl] Could not export Excellon file.')
  3964. return
  3965. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  3966. else:
  3967. ret = make_excellon()
  3968. if ret == 'fail':
  3969. self.inform.emit('[error_notcl] Could not export Excellon file.')
  3970. return
  3971. def export_dxf(self, obj_name, filename, use_thread=True):
  3972. """
  3973. Exports a Geometry Object to an DXF file.
  3974. :param filename: Path to the DXF file to save to.
  3975. :return:
  3976. """
  3977. if filename is None:
  3978. filename = self.defaults["global_last_save_folder"]
  3979. self.log.debug("export_dxf()")
  3980. format_exc = ''
  3981. units = ''
  3982. try:
  3983. obj = self.collection.get_by_name(str(obj_name))
  3984. except:
  3985. # TODO: The return behavior has not been established... should raise exception?
  3986. return "Could not retrieve object: %s" % obj_name
  3987. # updated units
  3988. units = self.general_options_form.general_group.units_radio.get_value().upper()
  3989. if units == 'IN' or units == 'INCH':
  3990. units = 'INCH'
  3991. elif units == 'MM' or units == 'METIRC':
  3992. units ='METRIC'
  3993. def make_dxf():
  3994. try:
  3995. dxf_code = obj.export_dxf()
  3996. dxf_code.saveas(filename)
  3997. self.file_saved.emit("DXF", filename)
  3998. self.inform.emit("[success] DXF file exported to " + filename)
  3999. except:
  4000. return 'fail'
  4001. if use_thread is True:
  4002. with self.proc_container.new("Exporting DXF") as proc:
  4003. def job_thread_exc(app_obj):
  4004. ret = make_dxf()
  4005. if ret == 'fail':
  4006. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4007. return
  4008. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4009. else:
  4010. ret = make_dxf()
  4011. if ret == 'fail':
  4012. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4013. return
  4014. def import_svg(self, filename, geo_type='geometry', outname=None):
  4015. """
  4016. Adds a new Geometry Object to the projects and populates
  4017. it with shapes extracted from the SVG file.
  4018. :param filename: Path to the SVG file.
  4019. :param outname:
  4020. :return:
  4021. """
  4022. obj_type = ""
  4023. if geo_type is None or geo_type == "geometry":
  4024. obj_type = "geometry"
  4025. elif geo_type == "gerber":
  4026. obj_type = geo_type
  4027. else:
  4028. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4029. "Only Geometry and Gerber are supported")
  4030. return
  4031. units = self.general_options_form.general_group.units_radio.get_value().upper()
  4032. def obj_init(geo_obj, app_obj):
  4033. geo_obj.import_svg(filename, obj_type, units=units)
  4034. geo_obj.multigeo = False
  4035. with self.proc_container.new("Importing SVG") as proc:
  4036. # Object name
  4037. name = outname or filename.split('/')[-1].split('\\')[-1]
  4038. self.new_object(obj_type, name, obj_init, autoselected=False)
  4039. self.progress.emit(20)
  4040. # Register recent file
  4041. self.file_opened.emit("svg", filename)
  4042. # GUI feedback
  4043. self.inform.emit("[success] Opened: " + filename)
  4044. self.progress.emit(100)
  4045. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4046. """
  4047. Adds a new Geometry Object to the projects and populates
  4048. it with shapes extracted from the DXF file.
  4049. :param filename: Path to the DXF file.
  4050. :param outname:
  4051. :type putname: str
  4052. :return:
  4053. """
  4054. obj_type = ""
  4055. if geo_type is None or geo_type == "geometry":
  4056. obj_type = "geometry"
  4057. elif geo_type == "gerber":
  4058. obj_type = geo_type
  4059. else:
  4060. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4061. "Only Geometry and Gerber are supported")
  4062. return
  4063. units = self.general_options_form.general_group.units_radio.get_value().upper()
  4064. def obj_init(geo_obj, app_obj):
  4065. geo_obj.import_dxf(filename, obj_type, units=units)
  4066. geo_obj.multigeo = False
  4067. with self.proc_container.new("Importing DXF") as proc:
  4068. # Object name
  4069. name = outname or filename.split('/')[-1].split('\\')[-1]
  4070. self.new_object(obj_type, name, obj_init, autoselected=False)
  4071. self.progress.emit(20)
  4072. # Register recent file
  4073. self.file_opened.emit("dxf", filename)
  4074. # GUI feedback
  4075. self.inform.emit("[success] Opened: " + filename)
  4076. self.progress.emit(100)
  4077. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4078. """
  4079. Adds a new Geometry Object to the projects and populates
  4080. it with shapes extracted from the SVG file.
  4081. :param filename: Path to the SVG file.
  4082. :param outname:
  4083. :return:
  4084. """
  4085. obj_type = ""
  4086. if type is None or type == "geometry":
  4087. obj_type = "geometry"
  4088. elif type == "gerber":
  4089. obj_type = type
  4090. else:
  4091. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4092. "Only Geometry and Gerber are supported")
  4093. return
  4094. def obj_init(geo_obj, app_obj):
  4095. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4096. geo_obj.multigeo = False
  4097. with self.proc_container.new("Importing Image") as proc:
  4098. # Object name
  4099. name = outname or filename.split('/')[-1].split('\\')[-1]
  4100. units = self.general_options_form.general_group.units_radio.get_value()
  4101. self.new_object(obj_type, name, obj_init)
  4102. self.progress.emit(20)
  4103. # Register recent file
  4104. self.file_opened.emit("image", filename)
  4105. # GUI feedback
  4106. self.inform.emit("[success] Opened: " + filename)
  4107. self.progress.emit(100)
  4108. def open_gerber(self, filename, follow=False, outname=None):
  4109. """
  4110. Opens a Gerber file, parses it and creates a new object for
  4111. it in the program. Thread-safe.
  4112. :param outname: Name of the resulting object. None causes the
  4113. name to be that of the file.
  4114. :param filename: Gerber file filename
  4115. :type filename: str
  4116. :param follow: If true, the parser will not create polygons, just lines
  4117. following the gerber path.
  4118. :type follow: bool
  4119. :return: None
  4120. """
  4121. # How the object should be initialized
  4122. def obj_init(gerber_obj, app_obj):
  4123. assert isinstance(gerber_obj, FlatCAMGerber), \
  4124. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4125. # Opening the file happens here
  4126. self.progress.emit(30)
  4127. try:
  4128. gerber_obj.parse_file(filename, follow=follow)
  4129. except IOError:
  4130. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4131. app_obj.progress.emit(0)
  4132. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4133. return "fail"
  4134. except ParseError as err:
  4135. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4136. app_obj.progress.emit(0)
  4137. self.log.error(str(err))
  4138. return "fail"
  4139. except:
  4140. msg = "[error] An internal error has ocurred. See shell.\n"
  4141. msg += traceback.format_exc()
  4142. app_obj.inform.emit(msg)
  4143. return "fail"
  4144. if gerber_obj.is_empty():
  4145. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4146. # self.collection.set_active(gerber_obj.options["name"])
  4147. # self.collection.delete_active()
  4148. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4149. return "fail"
  4150. # Further parsing
  4151. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4152. if follow is False:
  4153. App.log.debug("open_gerber()")
  4154. else:
  4155. App.log.debug("open_gerber() with 'follow' attribute")
  4156. with self.proc_container.new("Opening Gerber") as proc:
  4157. self.progress.emit(10)
  4158. # Object name
  4159. name = outname or filename.split('/')[-1].split('\\')[-1]
  4160. ### Object creation ###
  4161. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4162. if ret == 'fail':
  4163. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4164. return
  4165. # Register recent file
  4166. self.file_opened.emit("gerber", filename)
  4167. self.progress.emit(100)
  4168. # GUI feedback
  4169. self.inform.emit("[success] Opened: " + filename)
  4170. def open_excellon(self, filename, outname=None):
  4171. """
  4172. Opens an Excellon file, parses it and creates a new object for
  4173. it in the program. Thread-safe.
  4174. :param outname: Name of the resulting object. None causes the
  4175. name to be that of the file.
  4176. :param filename: Excellon file filename
  4177. :type filename: str
  4178. :return: None
  4179. """
  4180. App.log.debug("open_excellon()")
  4181. #self.progress.emit(10)
  4182. # How the object should be initialized
  4183. def obj_init(excellon_obj, app_obj):
  4184. # self.progress.emit(20)
  4185. try:
  4186. ret = excellon_obj.parse_file(filename)
  4187. if ret == "fail":
  4188. self.inform.emit("[error_notcl] This is not Excellon file.")
  4189. return "fail"
  4190. except IOError:
  4191. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4192. self.progress.emit(0) # TODO: self and app_bjj mixed
  4193. return "fail"
  4194. except:
  4195. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4196. msg += traceback.format_exc()
  4197. app_obj.inform.emit(msg)
  4198. return "fail"
  4199. ret = excellon_obj.create_geometry()
  4200. if ret == 'fail':
  4201. return "fail"
  4202. if excellon_obj.is_empty():
  4203. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4204. return "fail"
  4205. with self.proc_container.new("Opening Excellon."):
  4206. # Object name
  4207. name = outname or filename.split('/')[-1].split('\\')[-1]
  4208. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4209. if ret == 'fail':
  4210. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4211. return
  4212. # Register recent file
  4213. self.file_opened.emit("excellon", filename)
  4214. # GUI feedback
  4215. self.inform.emit("[success] Opened: " + filename)
  4216. # self.progress.emit(100)
  4217. def open_gcode(self, filename, outname=None):
  4218. """
  4219. Opens a G-gcode file, parses it and creates a new object for
  4220. it in the program. Thread-safe.
  4221. :param outname: Name of the resulting object. None causes the
  4222. name to be that of the file.
  4223. :param filename: G-code file filename
  4224. :type filename: str
  4225. :return: None
  4226. """
  4227. App.log.debug("open_gcode()")
  4228. # How the object should be initialized
  4229. def obj_init(job_obj, app_obj_):
  4230. """
  4231. :type app_obj_: App
  4232. """
  4233. assert isinstance(app_obj_, App), \
  4234. "Initializer expected App, got %s" % type(app_obj_)
  4235. self.progress.emit(10)
  4236. try:
  4237. f = open(filename)
  4238. gcode = f.read()
  4239. f.close()
  4240. except IOError:
  4241. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4242. self.progress.emit(0)
  4243. return "fail"
  4244. job_obj.gcode = gcode
  4245. self.progress.emit(20)
  4246. ret = job_obj.gcode_parse()
  4247. if ret == "fail":
  4248. self.inform.emit("[error_notcl] This is not GCODE")
  4249. return "fail"
  4250. self.progress.emit(60)
  4251. job_obj.create_geometry()
  4252. with self.proc_container.new("Opening G-Code."):
  4253. # Object name
  4254. name = outname or filename.split('/')[-1].split('\\')[-1]
  4255. # New object creation and file processing
  4256. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4257. if ret == 'fail':
  4258. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4259. "Attempting to create a FlatCAM CNCJob Object from "
  4260. "G-Code file failed during processing")
  4261. return "fail"
  4262. # Register recent file
  4263. self.file_opened.emit("cncjob", filename)
  4264. # GUI feedback
  4265. self.inform.emit("[success] Opened: " + filename)
  4266. self.progress.emit(100)
  4267. def open_project(self, filename, run_from_arg=None):
  4268. """
  4269. Loads a project from the specified file.
  4270. 1) Loads and parses file
  4271. 2) Registers the file as recently opened.
  4272. 3) Calls on_file_new()
  4273. 4) Updates options
  4274. 5) Calls new_object() with the object's from_dict() as init method.
  4275. 6) Calls plot_all()
  4276. :param filename: Name of the file from which to load.
  4277. :type filename: str
  4278. :return: None
  4279. """
  4280. App.log.debug("Opening project: " + filename)
  4281. # Open and parse
  4282. try:
  4283. f = open(filename, 'r')
  4284. except IOError:
  4285. App.log.error("Failed to open project file: %s" % filename)
  4286. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4287. return
  4288. try:
  4289. d = json.load(f, object_hook=dict2obj)
  4290. except:
  4291. App.log.error("Failed to parse project file: %s" % filename)
  4292. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4293. f.close()
  4294. return
  4295. self.file_opened.emit("project", filename)
  4296. # Clear the current project
  4297. ## NOT THREAD SAFE ##
  4298. if run_from_arg is True:
  4299. pass
  4300. else:
  4301. self.on_file_new()
  4302. #Project options
  4303. self.options.update(d['options'])
  4304. self.project_filename = filename
  4305. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4306. self.set_screen_units(self.options["units"])
  4307. # Re create objects
  4308. App.log.debug("Re-creating objects...")
  4309. for obj in d['objs']:
  4310. def obj_init(obj_inst, app_inst):
  4311. obj_inst.from_dict(obj)
  4312. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4313. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4314. # self.plot_all()
  4315. self.inform.emit("[success] Project loaded from: " + filename)
  4316. App.log.debug("Project loaded")
  4317. def propagate_defaults(self, silent=False):
  4318. """
  4319. This method is used to set default values in classes. It's
  4320. an alternative to project options but allows the use
  4321. of values invisible to the user.
  4322. :return: None
  4323. """
  4324. if silent is False:
  4325. self.log.debug("propagate_defaults()")
  4326. # Which objects to update the given parameters.
  4327. routes = {
  4328. "global_zdownrate": CNCjob,
  4329. "excellon_zeros": Excellon,
  4330. "excellon_format_upper_in": Excellon,
  4331. "excellon_format_lower_in": Excellon,
  4332. "excellon_format_upper_mm": Excellon,
  4333. "excellon_format_lower_mm": Excellon,
  4334. "excellon_units": Excellon,
  4335. "gerber_use_buffer_for_union": Gerber,
  4336. "geometry_multidepth": Geometry
  4337. }
  4338. for param in routes:
  4339. if param in routes[param].defaults:
  4340. try:
  4341. routes[param].defaults[param] = self.defaults[param]
  4342. if silent is False:
  4343. self.log.debug(" " + param + " OK")
  4344. except KeyError:
  4345. if silent is False:
  4346. self.log.debug(" ERROR: " + param + " not in defaults.")
  4347. else:
  4348. # Try extracting the name:
  4349. # classname_param here is param in the object
  4350. if param.find(routes[param].__name__.lower() + "_") == 0:
  4351. p = param[len(routes[param].__name__) + 1:]
  4352. if p in routes[param].defaults:
  4353. routes[param].defaults[p] = self.defaults[param]
  4354. if silent is False:
  4355. self.log.debug(" " + param + " OK!")
  4356. def restore_main_win_geom(self):
  4357. try:
  4358. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4359. self.defaults["global_def_win_y"],
  4360. self.defaults["global_def_win_w"],
  4361. self.defaults["global_def_win_h"])
  4362. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4363. except KeyError:
  4364. pass
  4365. def plot_all(self):
  4366. """
  4367. Re-generates all plots from all objects.
  4368. :return: None
  4369. """
  4370. self.log.debug("Plot_all()")
  4371. for obj in self.collection.get_list():
  4372. def worker_task(obj):
  4373. with self.proc_container.new("Plotting"):
  4374. obj.plot()
  4375. self.object_plotted.emit(obj)
  4376. # Send to worker
  4377. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4378. # self.progress.emit(10)
  4379. #
  4380. # def worker_task(app_obj):
  4381. # print "worker task"
  4382. # percentage = 0.1
  4383. # try:
  4384. # delta = 0.9 / len(self.collection.get_list())
  4385. # except ZeroDivisionError:
  4386. # self.progress.emit(0)
  4387. # return
  4388. # for obj in self.collection.get_list():
  4389. # with self.proc_container.new("Plotting"):
  4390. # obj.plot()
  4391. # app_obj.object_plotted.emit(obj)
  4392. #
  4393. # percentage += delta
  4394. # self.progress.emit(int(percentage*100))
  4395. #
  4396. # self.progress.emit(0)
  4397. # self.plots_updated.emit()
  4398. #
  4399. # # Send to worker
  4400. # #self.worker.add_task(worker_task, [self])
  4401. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4402. def register_folder(self, filename):
  4403. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4404. def register_save_folder(self, filename):
  4405. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4406. def set_progress_bar(self, percentage, text=""):
  4407. self.ui.progress_bar.setValue(int(percentage))
  4408. def setup_shell(self):
  4409. """
  4410. Creates shell functions. Runs once at startup.
  4411. :return: None
  4412. """
  4413. self.log.debug("setup_shell()")
  4414. def shelp(p=None):
  4415. if not p:
  4416. return "Available commands:\n" + \
  4417. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4418. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4419. if p not in commands:
  4420. return "Unknown command: %s" % p
  4421. return commands[p]["help"]
  4422. # --- Migrated to new architecture ---
  4423. # def options(name):
  4424. # ops = self.collection.get_by_name(str(name)).options
  4425. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4426. def h(*args):
  4427. """
  4428. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4429. and standalone parameters into list.
  4430. """
  4431. kwa = {}
  4432. a = []
  4433. n = len(args)
  4434. name = None
  4435. for i in range(n):
  4436. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4437. if match:
  4438. assert name is None
  4439. name = match.group(1)
  4440. continue
  4441. if name is None:
  4442. a.append(args[i])
  4443. else:
  4444. kwa[name] = args[i]
  4445. name = None
  4446. return a, kwa
  4447. @contextmanager
  4448. def wait_signal(signal, timeout=10000):
  4449. """
  4450. Block loop until signal emitted, timeout (ms) elapses
  4451. or unhandled exception happens in a thread.
  4452. :param signal: Signal to wait for.
  4453. """
  4454. loop = QtCore.QEventLoop()
  4455. # Normal termination
  4456. signal.connect(loop.quit)
  4457. # Termination by exception in thread
  4458. self.thread_exception.connect(loop.quit)
  4459. status = {'timed_out': False}
  4460. def report_quit():
  4461. status['timed_out'] = True
  4462. loop.quit()
  4463. yield
  4464. # Temporarily change how exceptions are managed.
  4465. oeh = sys.excepthook
  4466. ex = []
  4467. def except_hook(type_, value, traceback_):
  4468. ex.append(value)
  4469. oeh(type_, value, traceback_)
  4470. sys.excepthook = except_hook
  4471. # Terminate on timeout
  4472. if timeout is not None:
  4473. QtCore.QTimer.singleShot(timeout, report_quit)
  4474. #### Block ####
  4475. loop.exec_()
  4476. # Restore exception management
  4477. sys.excepthook = oeh
  4478. if ex:
  4479. self.raiseTclError(str(ex[0]))
  4480. if status['timed_out']:
  4481. raise Exception('Timed out!')
  4482. def make_docs():
  4483. output = ''
  4484. import collections
  4485. od = collections.OrderedDict(sorted(commands.items()))
  4486. for cmd_, val in od.items():
  4487. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4488. t = val['help']
  4489. usage_i = t.find('>')
  4490. if usage_i < 0:
  4491. expl = t
  4492. output += expl + '\n\n'
  4493. continue
  4494. expl = t[:usage_i - 1]
  4495. output += expl + '\n\n'
  4496. end_usage_i = t[usage_i:].find('\n')
  4497. if end_usage_i < 0:
  4498. end_usage_i = len(t[usage_i:])
  4499. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4500. else:
  4501. extras = t[usage_i+end_usage_i+1:]
  4502. parts = [s.strip() for s in extras.split('\n')]
  4503. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4504. for p in parts:
  4505. output += ' ' + p + '\n\n'
  4506. return output
  4507. '''
  4508. Howto implement TCL shell commands:
  4509. All parameters passed to command should be possible to set as None and test it afterwards.
  4510. This is because we need to see error caused in tcl,
  4511. if None value as default parameter is not allowed TCL will return empty error.
  4512. Use:
  4513. def mycommand(name=None,...):
  4514. Test it like this:
  4515. if name is None:
  4516. self.raise_tcl_error('Argument name is missing.')
  4517. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4518. otherwise we will miss it and processing will silently continue.
  4519. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4520. which is catched in exec_command and displayed in TCL shell console with red background.
  4521. Error in console is displayed with TCL trace.
  4522. This behavior works only within main thread,
  4523. errors with promissed tasks can be catched and detected only with log.
  4524. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4525. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4526. '''
  4527. commands = {
  4528. 'help': {
  4529. 'fcn': shelp,
  4530. 'help': "Shows list of commands."
  4531. },
  4532. }
  4533. # Import/overwrite tcl commands as objects of TclCommand descendants
  4534. # This modifies the variable 'commands'.
  4535. tclCommands.register_all_commands(self, commands)
  4536. # Add commands to the tcl interpreter
  4537. for cmd in commands:
  4538. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4539. # Make the tcl puts function return instead of print to stdout
  4540. self.tcl.eval('''
  4541. rename puts original_puts
  4542. proc puts {args} {
  4543. if {[llength $args] == 1} {
  4544. return "[lindex $args 0]"
  4545. } else {
  4546. eval original_puts $args
  4547. }
  4548. }
  4549. ''')
  4550. def setup_recent_items(self):
  4551. # TODO: Move this to constructor
  4552. icons = {
  4553. "gerber": "share/flatcam_icon16.png",
  4554. "excellon": "share/drill16.png",
  4555. "cncjob": "share/cnc16.png",
  4556. "project": "share/project16.png",
  4557. "svg": "share/geometry16.png",
  4558. "dxf": "share/dxf16.png",
  4559. "image": "share/image16.png"
  4560. }
  4561. openers = {
  4562. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4563. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4564. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4565. 'project': self.open_project,
  4566. 'svg': self.import_svg,
  4567. 'dxf': self.import_dxf,
  4568. 'image': self.import_image
  4569. }
  4570. # Open file
  4571. try:
  4572. f = open(self.data_path + '/recent.json')
  4573. except IOError:
  4574. App.log.error("Failed to load recent item list.")
  4575. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4576. return
  4577. try:
  4578. self.recent = json.load(f)
  4579. except json.scanner.JSONDecodeError:
  4580. App.log.error("Failed to parse recent item list.")
  4581. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4582. f.close()
  4583. return
  4584. f.close()
  4585. # Closure needed to create callbacks in a loop.
  4586. # Otherwise late binding occurs.
  4587. def make_callback(func, fname):
  4588. def opener():
  4589. func(fname)
  4590. return opener
  4591. def reset_recent():
  4592. # Reset menu
  4593. self.ui.recent.clear()
  4594. self.recent = []
  4595. try:
  4596. f = open(self.data_path + '/recent.json', 'w')
  4597. except IOError:
  4598. App.log.error("Failed to open recent items file for writing.")
  4599. return
  4600. json.dump(self.recent, f)
  4601. # Reset menu
  4602. self.ui.recent.clear()
  4603. # Create menu items
  4604. for recent in self.recent:
  4605. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4606. try:
  4607. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4608. # Attach callback
  4609. o = make_callback(openers[recent["kind"]], recent['filename'])
  4610. action.triggered.connect(o)
  4611. self.ui.recent.addAction(action)
  4612. except KeyError:
  4613. App.log.error("Unsupported file type: %s" % recent["kind"])
  4614. # Last action in Recent Files menu is one that Clear the content
  4615. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  4616. clear_action.triggered.connect(reset_recent)
  4617. self.ui.recent.addSeparator()
  4618. self.ui.recent.addAction(clear_action)
  4619. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  4620. # self.ui.menufilerecent.set_submenu(recent_menu)
  4621. # recent_menu.show_all()
  4622. # self.ui.recent.show()
  4623. self.log.debug("Recent items list has been populated.")
  4624. def setup_component_editor(self):
  4625. label = QtWidgets.QLabel("Choose an item from Project")
  4626. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  4627. self.ui.selected_scroll_area.setWidget(label)
  4628. def setup_obj_classes(self):
  4629. """
  4630. Sets up application specifics on the FlatCAMObj class.
  4631. :return: None
  4632. """
  4633. FlatCAMObj.app = self
  4634. ObjectCollection.app = self
  4635. FCProcess.app = self
  4636. FCProcessContainer.app = self
  4637. def version_check(self):
  4638. """
  4639. Checks for the latest version of the program. Alerts the
  4640. user if theirs is outdated. This method is meant to be run
  4641. in a separate thread.
  4642. :return: None
  4643. """
  4644. self.log.debug("version_check()")
  4645. full_url = App.version_url + \
  4646. "?s=" + str(self.defaults['serial']) + \
  4647. "&v=" + str(self.version) + \
  4648. "&os=" + str(self.os) + \
  4649. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  4650. App.log.debug("Checking for updates @ %s" % full_url)
  4651. ### Get the data
  4652. try:
  4653. f = urllib.request.urlopen(full_url)
  4654. except:
  4655. # App.log.warning("Failed checking for latest version. Could not connect.")
  4656. self.log.warning("Failed checking for latest version. Could not connect.")
  4657. self.inform.emit("[warning] Failed checking for latest version. Could not connect.")
  4658. return
  4659. try:
  4660. data = json.load(f)
  4661. except Exception as e:
  4662. App.log.error("Could not parse information about latest version.")
  4663. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  4664. App.log.debug("json.load(): %s" % str(e))
  4665. f.close()
  4666. return
  4667. f.close()
  4668. ### Latest version?
  4669. if self.version >= data["version"]:
  4670. App.log.debug("FlatCAM is up to date!")
  4671. self.inform.emit("[success] FlatCAM is up to date!")
  4672. return
  4673. App.log.debug("Newer version available.")
  4674. self.message.emit(
  4675. "Newer Version Available",
  4676. str("There is a newer version of FlatCAM " +
  4677. "available for download:<br><br>" +
  4678. "<B>" + data["name"] + "</b><br>" +
  4679. data["message"].replace("\n", "<br>")),
  4680. "info"
  4681. )
  4682. def enable_plots(self, objects):
  4683. def worker_task(app_obj):
  4684. percentage = 0.1
  4685. try:
  4686. delta = 0.9 / len(objects)
  4687. except ZeroDivisionError:
  4688. self.progress.emit(0)
  4689. return
  4690. for obj in objects:
  4691. obj.options['plot'] = True
  4692. percentage += delta
  4693. self.progress.emit(int(percentage*100))
  4694. self.progress.emit(0)
  4695. self.plots_updated.emit()
  4696. self.collection.update_view()
  4697. # Send to worker
  4698. # self.worker.add_task(worker_task, [self])
  4699. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4700. def disable_plots(self, objects):
  4701. # TODO: This method is very similar to replot_all. Try to merge.
  4702. """
  4703. Disables plots
  4704. :param objects: list
  4705. Objects to be disabled
  4706. :return:
  4707. """
  4708. self.progress.emit(10)
  4709. def worker_task(app_obj):
  4710. percentage = 0.1
  4711. try:
  4712. delta = 0.9 / len(objects)
  4713. except ZeroDivisionError:
  4714. self.progress.emit(0)
  4715. return
  4716. for obj in objects:
  4717. obj.options['plot'] = False
  4718. percentage += delta
  4719. self.progress.emit(int(percentage*100))
  4720. self.progress.emit(0)
  4721. self.plots_updated.emit()
  4722. self.collection.update_view()
  4723. # Send to worker
  4724. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4725. def clear_plots(self):
  4726. objects = self.collection.get_list()
  4727. for obj in objects:
  4728. obj.clear(obj == objects[-1])
  4729. # Clear pool to free memory
  4730. self.clear_pool()
  4731. def generate_cnc_job(self, objects):
  4732. for obj in objects:
  4733. obj.generatecncjob()
  4734. def save_project(self, filename):
  4735. """
  4736. Saves the current project to the specified file.
  4737. :param filename: Name of the file in which to save.
  4738. :type filename: str
  4739. :return: None
  4740. """
  4741. self.log.debug("save_project()")
  4742. with self.proc_container.new("Saving FlatCAM Project") as proc:
  4743. ## Capture the latest changes
  4744. # Current object
  4745. try:
  4746. self.collection.get_active().read_form()
  4747. except:
  4748. self.log.debug("[warning] There was no active object")
  4749. pass
  4750. # Project options
  4751. self.options_read_form()
  4752. # Serialize the whole project
  4753. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  4754. "options": self.options,
  4755. "version": self.version}
  4756. # Open file
  4757. try:
  4758. f = open(filename, 'w')
  4759. except IOError:
  4760. App.log.error("[error] Failed to open file for saving: %s", filename)
  4761. return
  4762. # Write
  4763. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  4764. f.close()
  4765. # verification of the saved project
  4766. # Open and parse
  4767. try:
  4768. saved_f = open(filename, 'r')
  4769. except IOError:
  4770. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  4771. return
  4772. try:
  4773. saved_d = json.load(saved_f, object_hook=dict2obj)
  4774. except:
  4775. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  4776. f.close()
  4777. return
  4778. saved_f.close()
  4779. if 'version' in saved_d:
  4780. self.inform.emit("[success] Project saved to: %s" % filename)
  4781. else:
  4782. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  4783. def on_options_app2project(self):
  4784. """
  4785. Callback for Options->Transfer Options->App=>Project. Copies options
  4786. from application defaults to project defaults.
  4787. :return: None
  4788. """
  4789. self.report_usage("on_options_app2project")
  4790. self.defaults_read_form()
  4791. self.options.update(self.defaults)
  4792. self.options_write_form()
  4793. def on_options_project2app(self):
  4794. """
  4795. Callback for Options->Transfer Options->Project=>App. Copies options
  4796. from project defaults to application defaults.
  4797. :return: None
  4798. """
  4799. self.report_usage("on_options_project2app")
  4800. self.options_read_form()
  4801. self.defaults.update(self.options)
  4802. self.defaults_write_form()
  4803. def on_options_project2object(self):
  4804. """
  4805. Callback for Options->Transfer Options->Project=>Object. Copies options
  4806. from project defaults to the currently selected object.
  4807. :return: None
  4808. """
  4809. self.report_usage("on_options_project2object")
  4810. self.options_read_form()
  4811. obj = self.collection.get_active()
  4812. if obj is None:
  4813. self.inform.emit("WARNING: No object selected.")
  4814. return
  4815. for option in self.options:
  4816. if option.find(obj.kind + "_") == 0:
  4817. oname = option[len(obj.kind) + 1:]
  4818. obj.options[oname] = self.options[option]
  4819. obj.to_form() # Update UI
  4820. def on_options_object2project(self):
  4821. """
  4822. Callback for Options->Transfer Options->Object=>Project. Copies options
  4823. from the currently selected object to project defaults.
  4824. :return: None
  4825. """
  4826. self.report_usage("on_options_object2project")
  4827. obj = self.collection.get_active()
  4828. if obj is None:
  4829. self.inform.emit("WARNING: No object selected.")
  4830. return
  4831. obj.read_form()
  4832. for option in obj.options:
  4833. if option in ['name']: # TODO: Handle this better...
  4834. continue
  4835. self.options[obj.kind + "_" + option] = obj.options[option]
  4836. self.options_write_form()
  4837. def on_options_object2app(self):
  4838. """
  4839. Callback for Options->Transfer Options->Object=>App. Copies options
  4840. from the currently selected object to application defaults.
  4841. :return: None
  4842. """
  4843. self.report_usage("on_options_object2app")
  4844. obj = self.collection.get_active()
  4845. if obj is None:
  4846. self.inform.emit("WARNING: No object selected.")
  4847. return
  4848. obj.read_form()
  4849. for option in obj.options:
  4850. if option in ['name']: # TODO: Handle this better...
  4851. continue
  4852. self.defaults[obj.kind + "_" + option] = obj.options[option]
  4853. self.defaults_write_form()
  4854. def on_options_app2object(self):
  4855. """
  4856. Callback for Options->Transfer Options->App=>Object. Copies options
  4857. from application defaults to the currently selected object.
  4858. :return: None
  4859. """
  4860. self.report_usage("on_options_app2object")
  4861. self.defaults_read_form()
  4862. obj = self.collection.get_active()
  4863. if obj is None:
  4864. self.inform.emit("WARNING: No object selected.")
  4865. return
  4866. for option in self.defaults:
  4867. if option.find(obj.kind + "_") == 0:
  4868. oname = option[len(obj.kind) + 1:]
  4869. obj.options[oname] = self.defaults[option]
  4870. obj.to_form() # Update UI
  4871. # end of file