FlatCAMApp.py 379 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592
  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 urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. # ##################################### ##
  23. # # Imports part of FlatCAM # ##
  24. # ##################################### ##
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. import builtins
  45. fcTranslate.apply_language('strings')
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  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.918
  80. version_date = "2019/06/11"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. # ############### ##
  99. # # Signals # ##
  100. # ############### ##
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. self.main_thread = QtWidgets.QApplication.instance().thread()
  149. # ################ ##
  150. # # ## OS-specific # ##
  151. # ################ ##
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  163. self.os = 'unix'
  164. # ############################ ##
  165. # # ## Setup folders and files # ##
  166. # ############################ ##
  167. if not os.path.exists(self.data_path):
  168. os.makedirs(self.data_path)
  169. App.log.debug('Created data folder: ' + self.data_path)
  170. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  171. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  172. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  173. if not os.path.exists(self.postprocessorpaths):
  174. os.makedirs(self.postprocessorpaths)
  175. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  176. # create current_defaults.FlatConfig file if there is none
  177. try:
  178. f = open(self.data_path + '/current_defaults.FlatConfig')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty current_defaults.FlatConfig')
  182. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. # create factory_defaults.FlatConfig file if there is none
  186. try:
  187. f = open(self.data_path + '/factory_defaults.FlatConfig')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty factory_defaults.FlatConfig')
  191. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  192. json.dump({}, f)
  193. f.close()
  194. try:
  195. f = open(self.data_path + '/recent.json')
  196. f.close()
  197. except IOError:
  198. App.log.debug('Creating empty recent.json')
  199. f = open(self.data_path + '/recent.json', 'w')
  200. json.dump([], f)
  201. f.close()
  202. # Application directory. CHDIR to it. Otherwise, trying to load
  203. # GUI icons will fail as their path is relative.
  204. # This will fail under cx_freeze ...
  205. self.app_home = os.path.dirname(os.path.realpath(__file__))
  206. App.log.debug("Application path is " + self.app_home)
  207. App.log.debug("Started in " + os.getcwd())
  208. # cx_freeze workaround
  209. if os.path.isfile(self.app_home):
  210. self.app_home = os.path.dirname(self.app_home)
  211. os.chdir(self.app_home)
  212. # Create multiprocessing pool
  213. self.pool = Pool()
  214. # variable to store mouse coordinates
  215. self.mouse = [0, 0]
  216. # ################# ##
  217. # # Initialize GUI # ##
  218. # ################# ##
  219. # FlatCAM colors used in plotting
  220. self.FC_light_green = '#BBF268BF'
  221. self.FC_dark_green = '#006E20BF'
  222. self.FC_light_blue = '#a5a5ffbf'
  223. self.FC_dark_blue = '#0000ffbf'
  224. QtCore.QObject.__init__(self)
  225. self.ui = FlatCAMGUI(self.version, self.beta, self)
  226. # self.connect(self.ui,
  227. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  228. # self.save_geometry) PyQt4
  229. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  230. self.ui.final_save.connect(self.final_save)
  231. # ########### ##
  232. # # ## Data ## ##
  233. # ########### ##
  234. self.recent = []
  235. self.clipboard = QtWidgets.QApplication.clipboard()
  236. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  237. self.project_filename = None
  238. self.toggle_units_ignore = False
  239. # self.defaults_form = PreferencesUI()
  240. # when adding entries here read the comments in the method found bellow named:
  241. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  242. self.defaults_form_fields = {
  243. # General App
  244. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  245. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  246. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  247. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  248. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  249. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  250. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  251. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  252. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  253. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  256. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  257. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  258. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  259. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  260. # General GUI Preferences
  261. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  262. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  263. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  264. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  265. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  266. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  267. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  268. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  269. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  270. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  271. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  272. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  273. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  274. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  275. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  276. # General GUI Settings
  277. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  278. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  279. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  280. # Gerber General
  281. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  282. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  283. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  284. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  285. # Gerber Options
  286. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  287. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  288. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  289. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  290. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  291. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  292. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  293. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  294. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  295. # Gerber Advanced Options
  296. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  297. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  298. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  299. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  300. # Gerber Export
  301. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  302. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  303. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  304. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  305. # Gerber Editor
  306. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  307. # Excellon General
  308. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  309. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  310. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  311. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  312. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  313. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  314. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  315. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  316. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  317. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  318. # Excellon Options
  319. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  320. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  321. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  322. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  323. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  324. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  325. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  326. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  327. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  328. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  329. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  330. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  331. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  332. # Excellon Advanced Options
  333. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  334. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  335. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  336. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  337. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  338. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  339. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  340. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  341. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  342. # Excellon Export
  343. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  344. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  345. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  346. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  347. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  348. # Geometry General
  349. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  350. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  351. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  352. # Geometry Options
  353. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  354. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  355. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  356. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  357. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  358. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  359. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  360. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  361. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  362. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  363. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  364. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  365. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  366. # Geometry Advanced Options
  367. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  368. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  369. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  370. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  371. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  372. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  373. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  374. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  375. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  376. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  377. # Geometry Editor
  378. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  379. # CNCJob General
  380. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  381. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  382. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  383. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  384. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  385. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  386. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  387. # CNC Job Options
  388. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  389. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  390. # CNC Job Advanced Options
  391. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  392. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  393. # NCC Tool
  394. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  395. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  396. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  397. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  398. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  399. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  400. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  401. # CutOut Tool
  402. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  403. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  404. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  405. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  406. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  407. # Paint Area Tool
  408. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  409. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  410. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  411. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  412. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  413. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  414. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  415. # 2-sided Tool
  416. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  417. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  418. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  419. # Film Tool
  420. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  421. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  422. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  423. # Panelize Tool
  424. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  425. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  426. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  427. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  428. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  429. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  430. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  431. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  432. # Calculators Tool
  433. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  434. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  435. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  436. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  437. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  438. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  439. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  440. # Transformations Tool
  441. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  442. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  443. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  444. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  445. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  446. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  447. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  448. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  449. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  450. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  451. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  452. # SolderPaste Dispensing Tool
  453. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  454. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  455. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  456. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  457. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  458. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  459. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  460. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  461. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  462. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  463. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  464. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  465. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  466. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  467. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  468. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  469. }
  470. # ########################## ##
  471. # # ## LOAD POSTPROCESSORS ## ##
  472. # ########################## ##
  473. self.postprocessors = load_postprocessors(self)
  474. for name in list(self.postprocessors.keys()):
  475. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  476. if name.partition('_')[0] == 'Paste':
  477. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  478. continue
  479. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  480. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  481. if name == 'hpgl':
  482. continue
  483. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  484. # ########################## ##
  485. # # ## LOAD LANGUAGES ## ##
  486. # ########################## ##
  487. self.languages = fcTranslate.load_languages()
  488. for name in sorted(self.languages.values()):
  489. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  490. self.defaults = LoudDict()
  491. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  492. self.defaults.update({
  493. # Global APP Preferences
  494. "global_serial": 0,
  495. "global_stats": {},
  496. "units": "IN",
  497. "global_app_level": 'b',
  498. "global_language": 'English',
  499. "global_version_check": True,
  500. "global_send_stats": True,
  501. "global_pan_button": '2',
  502. "global_mselect_key": 'Control',
  503. "global_project_at_startup": False,
  504. "global_project_autohide": True,
  505. "global_toggle_tooltips": True,
  506. "global_worker_number": 2,
  507. "global_tolerance": 0.01,
  508. "global_open_style": True,
  509. "global_compression_level": 3,
  510. "global_save_compressed": True,
  511. # Global GUI Preferences
  512. "global_gridx": 0.0393701,
  513. "global_gridy": 0.0393701,
  514. "global_snap_max": 0.001968504,
  515. "global_workspace": False,
  516. "global_workspaceT": "A4P",
  517. "global_grid_context_menu": {
  518. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  519. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  520. },
  521. "global_plot_fill": '#BBF268BF',
  522. "global_plot_line": '#006E20BF',
  523. "global_sel_fill": '#a5a5ffbf',
  524. "global_sel_line": '#0000ffbf',
  525. "global_alt_sel_fill": '#BBF268BF',
  526. "global_alt_sel_line": '#006E20BF',
  527. "global_draw_color": '#FF0000',
  528. "global_sel_draw_color": '#0000FF',
  529. "global_proj_item_color": '#000000',
  530. "global_proj_item_dis_color": '#b7b7cb',
  531. "global_toolbar_view": 511,
  532. "global_background_timeout": 300000, # Default value is 5 minutes
  533. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  534. # (python trace only for unknown errors),
  535. # 1 = show trace(show trace always),
  536. # 2 = (For the future).
  537. # Persistence
  538. "global_last_folder": None,
  539. "global_last_save_folder": None,
  540. # Default window geometry
  541. "global_def_win_x": 100,
  542. "global_def_win_y": 100,
  543. "global_def_win_w": 1024,
  544. "global_def_win_h": 650,
  545. "global_def_notebook_width": 1,
  546. # Constants...
  547. "global_defaults_save_period_ms": 20000, # Time between default saves.
  548. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  549. "global_shell_at_startup": False, # Show the shell at startup.
  550. "global_recent_limit": 10, # Max. items in recent list.
  551. "fit_key": 'V',
  552. "zoom_out_key": '-',
  553. "zoom_in_key": '=',
  554. "grid_toggle_key": 'G',
  555. "zoom_ratio": 1.5,
  556. "global_point_clipboard_format": "(%.4f, %.4f)",
  557. "global_zdownrate": None,
  558. # General GUI Settings
  559. "global_hover": False,
  560. "global_selection_shape": True,
  561. "global_layout": "compact",
  562. # Gerber General
  563. "gerber_plot": True,
  564. "gerber_solid": True,
  565. "gerber_multicolored": False,
  566. "gerber_isotooldia": 0.016,
  567. "gerber_isopasses": 1,
  568. "gerber_isooverlap": 0.15,
  569. # Gerber Options
  570. "gerber_combine_passes": False,
  571. "gerber_milling_type": "cl",
  572. "gerber_noncoppermargin": 0.1,
  573. "gerber_noncopperrounded": False,
  574. "gerber_bboxmargin": 0.1,
  575. "gerber_bboxrounded": False,
  576. "gerber_circle_steps": 128,
  577. "gerber_use_buffer_for_union": True,
  578. # Gerber Advanced Options
  579. "gerber_aperture_display": False,
  580. "gerber_aperture_scale_factor": 1.0,
  581. "gerber_aperture_buffer_factor": 0.0,
  582. "gerber_follow": False,
  583. # Gerber Export
  584. "gerber_exp_units": 'IN',
  585. "gerber_exp_integer": 2,
  586. "gerber_exp_decimals": 4,
  587. "gerber_exp_zeros": 'L',
  588. # Gerber Editor
  589. "gerber_editor_sel_limit": 30,
  590. # Excellon General
  591. "excellon_plot": True,
  592. "excellon_solid": True,
  593. "excellon_format_upper_in": 2,
  594. "excellon_format_lower_in": 4,
  595. "excellon_format_upper_mm": 3,
  596. "excellon_format_lower_mm": 3,
  597. "excellon_zeros": "L",
  598. "excellon_units": "INCH",
  599. "excellon_optimization_type": 'B',
  600. "excellon_search_time": 3,
  601. # Excellon Options
  602. "excellon_drillz": -0.1,
  603. "excellon_travelz": 0.1,
  604. "excellon_feedrate": 3.0,
  605. "excellon_spindlespeed": None,
  606. "excellon_spindledir": 'CW',
  607. "excellon_dwell": False,
  608. "excellon_dwelltime": 1,
  609. "excellon_toolchange": False,
  610. "excellon_toolchangez": 0.5,
  611. "excellon_ppname_e": 'default',
  612. "excellon_tooldia": 0.016,
  613. "excellon_slot_tooldia": 0.016,
  614. "excellon_gcode_type": "drills",
  615. # Excellon Advanced Options
  616. "excellon_offset": 0.0,
  617. "excellon_toolchangexy": "0.0, 0.0",
  618. "excellon_startz": None,
  619. "excellon_endz": 0.5,
  620. "excellon_feedrate_rapid": 3.0,
  621. "excellon_z_pdepth": -0.02,
  622. "excellon_feedrate_probe": 3.0,
  623. "excellon_f_plunge": False,
  624. "excellon_f_retract": False,
  625. # Excellon Export
  626. "excellon_exp_units": 'INCH',
  627. "excellon_exp_format": 'ndec',
  628. "excellon_exp_integer": 2,
  629. "excellon_exp_decimals": 4,
  630. "excellon_exp_zeros": 'LZ',
  631. # Geometry General
  632. "geometry_plot": True,
  633. "geometry_circle_steps": 128,
  634. "geometry_cnctooldia": 0.016,
  635. # Geometry Options
  636. "geometry_cutz": -0.002,
  637. "geometry_multidepth": False,
  638. "geometry_depthperpass": 0.002,
  639. "geometry_travelz": 0.1,
  640. "geometry_toolchange": False,
  641. "geometry_toolchangez": 0.5,
  642. "geometry_feedrate": 3.0,
  643. "geometry_feedrate_z": 3.0,
  644. "geometry_spindlespeed": None,
  645. "geometry_spindledir": 'CW',
  646. "geometry_dwell": False,
  647. "geometry_dwelltime": 1,
  648. "geometry_ppname_g": 'default',
  649. # Geometry Advanced Options
  650. "geometry_toolchangexy": "0.0, 0.0",
  651. "geometry_startz": None,
  652. "geometry_endz": 0.5,
  653. "geometry_feedrate_rapid": 3.0,
  654. "geometry_extracut": False,
  655. "geometry_z_pdepth": -0.02,
  656. "geometry_f_plunge": False,
  657. "geometry_feedrate_probe": 3.0,
  658. "geometry_segx": 0.0,
  659. "geometry_segy": 0.0,
  660. # Geometry Editor
  661. "geometry_editor_sel_limit": 30,
  662. # CNC Job General
  663. "cncjob_plot": True,
  664. "cncjob_plot_kind": 'all',
  665. "cncjob_annotation": True,
  666. "cncjob_tooldia": 0.0393701,
  667. "cncjob_coords_decimals": 4,
  668. "cncjob_fr_decimals": 2,
  669. "cncjob_steps_per_circle": 64,
  670. # CNC Job Options
  671. "cncjob_prepend": "",
  672. "cncjob_append": "",
  673. # CNC Job Advanced Options
  674. "cncjob_toolchange_macro": "",
  675. "cncjob_toolchange_macro_enable": False,
  676. "tools_ncctools": "0.0393701, 0.019685",
  677. "tools_nccoverlap": 0.015748,
  678. "tools_nccmargin": 0.00393701,
  679. "tools_nccmethod": "seed",
  680. "tools_nccconnect": True,
  681. "tools_ncccontour": True,
  682. "tools_nccrest": False,
  683. "tools_cutouttooldia": 0.00393701,
  684. "tools_cutoutmargin": 0.00393701,
  685. "tools_cutoutgapsize": 0.005905512,
  686. "tools_gaps_ff": "8",
  687. "tools_cutout_convexshape": False,
  688. "tools_painttooldia": 0.07,
  689. "tools_paintoverlap": 0.15,
  690. "tools_paintmargin": 0.0,
  691. "tools_paintmethod": "seed",
  692. "tools_selectmethod": "single",
  693. "tools_pathconnect": True,
  694. "tools_paintcontour": True,
  695. "tools_2sided_mirror_axis": "X",
  696. "tools_2sided_axis_loc": "point",
  697. "tools_2sided_drilldia": 0.0393701,
  698. "tools_film_type": 'neg',
  699. "tools_film_boundary": 0.0393701,
  700. "tools_film_scale": 0,
  701. "tools_panelize_spacing_columns": 0,
  702. "tools_panelize_spacing_rows": 0,
  703. "tools_panelize_columns": 1,
  704. "tools_panelize_rows": 1,
  705. "tools_panelize_constrain": False,
  706. "tools_panelize_constrainx": 0.0,
  707. "tools_panelize_constrainy": 0.0,
  708. "tools_panelize_panel_type": 'gerber',
  709. "tools_calc_vshape_tip_dia": 0.007874,
  710. "tools_calc_vshape_tip_angle": 30,
  711. "tools_calc_vshape_cut_z": 0.000787,
  712. "tools_calc_electro_length": 10.0,
  713. "tools_calc_electro_width": 10.0,
  714. "tools_calc_electro_cdensity":13.0,
  715. "tools_calc_electro_growth": 10.0,
  716. "tools_transform_rotate": 90,
  717. "tools_transform_skew_x": 0.0,
  718. "tools_transform_skew_y": 0.0,
  719. "tools_transform_scale_x": 1.0,
  720. "tools_transform_scale_y": 1.0,
  721. "tools_transform_scale_link": True,
  722. "tools_transform_scale_reference": True,
  723. "tools_transform_offset_x": 0.0,
  724. "tools_transform_offset_y": 0.0,
  725. "tools_transform_mirror_reference": False,
  726. "tools_transform_mirror_point": (0, 0),
  727. "tools_solderpaste_tools": "0.0393701, 0.011811",
  728. "tools_solderpaste_new": 0.011811,
  729. "tools_solderpaste_z_start": 0.00019685039,
  730. "tools_solderpaste_z_dispense": 0.00393701,
  731. "tools_solderpaste_z_stop": 0.00019685039,
  732. "tools_solderpaste_z_travel": 0.00393701,
  733. "tools_solderpaste_z_toolchange": 0.0393701,
  734. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  735. "tools_solderpaste_frxy": 3.0,
  736. "tools_solderpaste_frz": 3.0,
  737. "tools_solderpaste_frz_dispense": 0.0393701,
  738. "tools_solderpaste_speedfwd": 20,
  739. "tools_solderpaste_dwellfwd": 1,
  740. "tools_solderpaste_speedrev": 10,
  741. "tools_solderpaste_dwellrev": 1,
  742. "tools_solderpaste_pp": 'Paste_1'
  743. })
  744. # ############################ ##
  745. # # ## Load defaults from file # ##
  746. # ############################ ##
  747. if user_defaults:
  748. self.load_defaults(filename='current_defaults')
  749. # ######################### ##
  750. # #### APPLY APP LANGUAGE # ##
  751. # ######################### ##
  752. ret_val = fcTranslate.apply_language('strings')
  753. if ret_val == "no language":
  754. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  755. log.debug("Could not find the Language files. The App strings are missing.")
  756. else:
  757. # make the current language the current selection on the language combobox
  758. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  759. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  760. # ################################ ##
  761. # # ## CREATE UNIQUE SERIAL NUMBER # ##
  762. # ################################ ##
  763. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  764. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  765. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  766. self.save_defaults(silent=True)
  767. self.propagate_defaults(silent=True)
  768. self.restore_main_win_geom()
  769. def auto_save_defaults():
  770. try:
  771. self.save_defaults(silent=True)
  772. self.propagate_defaults(silent=True)
  773. finally:
  774. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  775. # the following lines activates automatic defaults save
  776. # if user_defaults:
  777. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  778. # self.options_form = PreferencesUI()
  779. self.options_form_fields = {
  780. "units": self.ui.general_options_form.general_app_group.units_radio,
  781. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  782. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  783. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  784. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  785. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  786. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  787. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  788. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  789. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  790. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  791. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  792. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  793. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  794. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  795. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  796. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  797. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  798. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  799. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  800. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  801. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  802. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  803. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  804. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  805. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  806. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  807. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  808. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  809. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  810. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  811. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  812. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  813. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  814. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  815. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  816. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  817. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  818. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  819. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  820. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  821. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  822. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  823. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  824. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  825. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  826. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  827. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  828. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  829. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  830. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  831. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  832. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  833. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  834. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  835. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  836. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  837. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  838. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  839. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  840. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  841. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  842. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  843. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  844. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  845. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  846. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  847. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  848. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  849. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  850. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  851. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  852. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  853. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  854. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  855. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  856. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  857. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  858. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  859. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  860. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  861. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  862. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  863. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  864. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  865. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  866. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  867. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  868. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  869. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  870. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  871. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  872. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  873. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  874. }
  875. for name in list(self.postprocessors.keys()):
  876. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  877. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  878. self.options = LoudDict()
  879. self.options.set_change_callback(self.on_options_dict_change)
  880. self.options.update({
  881. "units": "IN",
  882. "global_gridx": 1.0,
  883. "global_gridy": 1.0,
  884. "global_snap_max": 0.05,
  885. "global_background_timeout": 300000, # Default value is 5 minutes
  886. "global_verbose_error_level": 0, # Shell verbosity:
  887. # 0 = default(python trace only for unknown errors),
  888. # 1 = show trace(show trace allways), 2 = (For the future).
  889. "gerber_plot": True,
  890. "gerber_solid": True,
  891. "gerber_multicolored": False,
  892. "gerber_isotooldia": 0.016,
  893. "gerber_isopasses": 1,
  894. "gerber_isooverlap": 0.15,
  895. "gerber_combine_passes": True,
  896. "gerber_noncoppermargin": 0.0,
  897. "gerber_noncopperrounded": False,
  898. "gerber_bboxmargin": 0.0,
  899. "gerber_bboxrounded": False,
  900. "excellon_plot": True,
  901. "excellon_solid": False,
  902. "excellon_format_upper_in": 2,
  903. "excellon_format_lower_in": 4,
  904. "excellon_format_upper_mm": 3,
  905. "excellon_format_lower_mm": 3,
  906. "excellon_units": 'INCH',
  907. "excellon_optimization_type": 'B',
  908. "excellon_search_time": 3,
  909. "excellon_zeros": "L",
  910. "excellon_drillz": -0.1,
  911. "excellon_travelz": 0.1,
  912. "excellon_feedrate": 3.0,
  913. "excellon_feedrate_rapid": 3.0,
  914. "excellon_spindlespeed": None,
  915. "excellon_spindledir": 'CW',
  916. "excellon_dwell": True,
  917. "excellon_dwelltime": 1000,
  918. "excellon_toolchange": False,
  919. "excellon_toolchangez": 1.0,
  920. "excellon_toolchangexy": "0.0, 0.0",
  921. "excellon_tooldia": 0.016,
  922. "excellon_ppname_e": 'default',
  923. "excellon_f_plunge": False,
  924. "excellon_startz": None,
  925. "excellon_endz": 2.0,
  926. "geometry_plot": True,
  927. "geometry_segx": 0.0,
  928. "geometry_segy": 0.0,
  929. "geometry_cutz": -0.002,
  930. "geometry_travelz": 0.1,
  931. "geometry_feedrate": 3.0,
  932. "geometry_feedrate_z": 3.0,
  933. "geometry_feedrate_rapid": 3.0,
  934. "geometry_spindlespeed": None,
  935. "geometry_spindledir": 'CW',
  936. "geometry_dwell": True,
  937. "geometry_dwelltime": 1000,
  938. "geometry_cnctooldia": 0.016,
  939. "geometry_toolchange": False,
  940. "geometry_toolchangez": 2.0,
  941. "geometry_toolchangexy": "0.0, 0.0",
  942. "geometry_startz": None,
  943. "geometry_endz": 2.0,
  944. "geometry_ppname_g": "default",
  945. "geometry_f_plunge": False,
  946. "geometry_depthperpass": 0.002,
  947. "geometry_multidepth": False,
  948. "geometry_extracut": False,
  949. "cncjob_plot": True,
  950. "cncjob_tooldia": 0.016,
  951. "cncjob_prepend": "",
  952. "cncjob_append": "",
  953. "tools_ncctools": "1.0, 0.5",
  954. "tools_nccoverlap": 0.4,
  955. "tools_nccmargin": 1,
  956. "tools_cutouttooldia": 0.07,
  957. "tools_cutoutmargin": 0.1,
  958. "tools_cutoutgapsize": 0.15,
  959. "tools_gaps_ff": "8",
  960. "tools_painttooldia": 0.07,
  961. "tools_paintoverlap": 0.15,
  962. "tools_paintmargin": 0.0,
  963. "tools_paintmethod": "seed",
  964. "tools_selectmethod": "single",
  965. "tools_pathconnect": True,
  966. "tools_paintcontour": True,
  967. "tools_2sided_mirror_axis": "X",
  968. "tools_2sided_axis_loc": 'point',
  969. "tools_2sided_drilldia": 1,
  970. "tools_film_type": 'neg',
  971. "tools_film_boundary": 1,
  972. "tools_film_scale": 0,
  973. "tools_panelize_spacing_columns": 0,
  974. "tools_panelize_spacing_rows": 0,
  975. "tools_panelize_columns": 1,
  976. "tools_panelize_rows": 1,
  977. "tools_panelize_constrain": False,
  978. "tools_panelize_constrainx": 0.0,
  979. "tools_panelize_constrainy": 0.0
  980. })
  981. self.options.update(self.defaults) # Copy app defaults to project options
  982. self.gen_form = None
  983. self.ger_form = None
  984. self.exc_form = None
  985. self.geo_form = None
  986. self.cnc_form = None
  987. self.tools_form = None
  988. self.on_options_combo_change(0) # Will show the initial form
  989. # # ## Define OBJECT COLLECTION # ##
  990. self.collection = ObjectCollection(self)
  991. self.ui.project_tab_layout.addWidget(self.collection.view)
  992. # # ##
  993. self.log.debug("Finished creating Object Collection.")
  994. # # ## Initialize the color box's color in Preferences -> Global -> Color
  995. # Init Plot Colors
  996. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  997. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  998. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  999. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1000. int(self.defaults['global_plot_fill'][7:9], 16))
  1001. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1002. int(self.defaults['global_plot_fill'][7:9], 16))
  1003. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1004. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1005. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1006. # Init Left-Right Selection colors
  1007. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1008. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1009. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1010. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1011. int(self.defaults['global_sel_fill'][7:9], 16))
  1012. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1013. int(self.defaults['global_sel_fill'][7:9], 16))
  1014. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1015. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1016. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1017. # Init Right-Left Selection colors
  1018. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1019. self.defaults['global_alt_sel_fill'])
  1020. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1021. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1022. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1023. int(self.defaults['global_sel_fill'][7:9], 16))
  1024. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1025. int(self.defaults['global_sel_fill'][7:9], 16))
  1026. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1027. self.defaults['global_alt_sel_line'])
  1028. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1029. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1030. # Init Draw color and Selection Draw Color
  1031. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1032. self.defaults['global_draw_color'])
  1033. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1034. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1035. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1036. self.defaults['global_sel_draw_color'])
  1037. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1038. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1039. # Init Project Items color
  1040. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1041. self.defaults['global_proj_item_color'])
  1042. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1043. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1044. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1045. self.defaults['global_proj_item_dis_color'])
  1046. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1047. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1048. # # ## End of Data ## ##
  1049. # # ## Plot Area ## ##
  1050. start_plot_time = time.time() # debug
  1051. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1052. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1053. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1054. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1055. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1056. # Keys over plot enabled
  1057. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1058. self.ui.splitter.setStretchFactor(1, 2)
  1059. # So it can receive key presses
  1060. self.plotcanvas.vispy_canvas.native.setFocus()
  1061. self.app_cursor = self.plotcanvas.new_cursor()
  1062. self.app_cursor.enabled = False
  1063. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1064. # depending on from where those tools are called different actions can be done
  1065. self.call_source = 'app'
  1066. end_plot_time = time.time()
  1067. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1068. # # ## EDITOR section
  1069. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1070. self.exc_editor = FlatCAMExcEditor(self)
  1071. self.grb_editor = FlatCAMGrbEditor(self)
  1072. # # ## Adjust tabs width ## ##
  1073. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1074. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1075. self.collection.view.setMinimumWidth(290)
  1076. self.log.debug("Finished adding FlatCAM Editor's.")
  1077. # # ## Worker ## ##
  1078. if self.defaults["global_worker_number"]:
  1079. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1080. else:
  1081. self.workers = WorkerStack(workers_number=2)
  1082. self.worker_task.connect(self.workers.add_task)
  1083. # # ## Signal handling # ##
  1084. # # ## Custom signals
  1085. self.inform.connect(self.info)
  1086. self.app_quit.connect(self.quit_application)
  1087. self.message.connect(self.message_dialog)
  1088. self.progress.connect(self.set_progress_bar)
  1089. self.object_created.connect(self.on_object_created)
  1090. self.object_changed.connect(self.on_object_changed)
  1091. self.object_plotted.connect(self.on_object_plotted)
  1092. self.plots_updated.connect(self.on_plots_updated)
  1093. self.file_opened.connect(self.register_recent)
  1094. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1095. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1096. # # ## Standard signals
  1097. # # ## Menu
  1098. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1099. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1100. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1101. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1102. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1103. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1104. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1105. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1106. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1107. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1108. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1109. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1110. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1111. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1112. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1113. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1114. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1115. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1116. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1117. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1118. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1119. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1120. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1121. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1122. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1123. self.ui.menufile_exit.triggered.connect(self.final_save)
  1124. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1125. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1126. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1127. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1128. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1129. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1130. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1131. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1132. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1133. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1134. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1135. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1136. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1137. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1138. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1139. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1140. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1141. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1142. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1143. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1144. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1145. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1146. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1147. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1148. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1149. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1150. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1151. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1152. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1153. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1154. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1155. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1156. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1157. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1158. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1159. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1160. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1161. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1162. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1163. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1164. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1165. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1166. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1167. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1168. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1169. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1170. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1171. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1172. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1173. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1174. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1175. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1176. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1177. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1178. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1179. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1180. # ToolBar signals
  1181. self.connect_toolbar_signals()
  1182. # Context Menu
  1183. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1184. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1185. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1186. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1187. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1188. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1189. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1190. self.ui.clearplot.triggered.connect(self.clear_plots)
  1191. self.ui.replot.triggered.connect(self.plot_all)
  1192. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1193. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1194. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1195. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1196. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1197. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1198. # Preferences Plot Area TAB
  1199. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1200. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1201. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1202. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1203. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1204. # ############################ ##
  1205. # # ## GUI PREFERENCES SIGNALS # ##
  1206. # ############################ ##
  1207. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1208. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1209. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1210. )
  1211. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1212. lambda: self.on_toggle_units(no_pref=False))
  1213. # ############################ ##
  1214. # # ## GUI PREFERENCES SIGNALS # ##
  1215. # ############################ ##
  1216. # Setting plot colors signals
  1217. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1218. self.on_pf_color_entry)
  1219. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1220. self.on_pf_color_button)
  1221. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1222. self.on_pf_color_spinner)
  1223. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1224. self.on_pf_color_slider)
  1225. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1226. self.on_pl_color_entry)
  1227. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1228. self.on_pl_color_button)
  1229. # Setting selection (left - right) colors signals
  1230. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1231. self.on_sf_color_entry)
  1232. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1233. self.on_sf_color_button)
  1234. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1235. self.on_sf_color_spinner)
  1236. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1237. self.on_sf_color_slider)
  1238. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1239. self.on_sl_color_entry)
  1240. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1241. self.on_sl_color_button)
  1242. # Setting selection (right - left) colors signals
  1243. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1244. self.on_alt_sf_color_entry)
  1245. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1246. self.on_alt_sf_color_button)
  1247. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1248. self.on_alt_sf_color_spinner)
  1249. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1250. self.on_alt_sf_color_slider)
  1251. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1252. self.on_alt_sl_color_entry)
  1253. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1254. self.on_alt_sl_color_button)
  1255. # Setting Editor Draw colors signals
  1256. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1257. self.on_draw_color_entry)
  1258. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1259. self.on_draw_color_button)
  1260. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1261. self.on_sel_draw_color_entry)
  1262. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1263. self.on_sel_draw_color_button)
  1264. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1265. self.on_proj_color_entry)
  1266. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1267. self.on_proj_color_button)
  1268. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1269. self.on_proj_color_dis_entry)
  1270. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1271. self.on_proj_color_dis_button)
  1272. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1273. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1274. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1275. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1276. self.on_cnc_custom_parameters)
  1277. # Modify G-CODE Plot Area TAB
  1278. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1279. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1280. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1281. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1282. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1283. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1284. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1285. # Object list
  1286. self.collection.view.activated.connect(self.on_row_activated)
  1287. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1288. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1289. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1290. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1291. self.on_excellon_defaults_button)
  1292. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1293. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1294. self.on_excellon_options_button)
  1295. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1296. self.tool_tab_locked = False
  1297. # decide if to show or hide the Notebook side of the screen at startup
  1298. if self.defaults["global_project_at_startup"] is True:
  1299. self.ui.splitter.setSizes([1, 1])
  1300. else:
  1301. self.ui.splitter.setSizes([0, 1])
  1302. # ################# ##
  1303. # # ## Other setups # ##
  1304. # ################# ##
  1305. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1306. self.setup_obj_classes()
  1307. self.setup_recent_items()
  1308. self.setup_component_editor()
  1309. # ########## ##
  1310. # # ## Shell # ##
  1311. # ########## ##
  1312. # # ##
  1313. # Auto-complete KEYWORDS
  1314. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1315. 'aligndrill', 'clear',
  1316. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1317. 'export_gcode',
  1318. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1319. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1320. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1321. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1322. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1323. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1324. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1325. ]
  1326. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1327. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1328. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1329. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1330. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1331. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1332. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1333. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1334. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1335. ]
  1336. self.tcl_keywords = [
  1337. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1338. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1339. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1340. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1341. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1342. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1343. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1344. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1345. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1346. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1347. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1348. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1349. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1350. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1351. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1352. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1353. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1354. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1355. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1356. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1357. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1358. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1359. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1360. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1361. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1362. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1363. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1364. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1365. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1366. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1367. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1368. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1369. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1370. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1371. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1372. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1373. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1374. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1375. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1376. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1377. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1378. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1379. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1380. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1381. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1382. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1383. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1384. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1385. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1386. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1387. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1388. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1389. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1390. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1391. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1392. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1393. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1394. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1395. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1396. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1397. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1398. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1399. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1400. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1401. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1402. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1403. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1404. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1405. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1406. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1407. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1408. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1409. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1410. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1411. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1412. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1413. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1414. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1415. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1416. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1417. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1418. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1419. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1420. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1421. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1422. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1423. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1424. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1425. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1426. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1427. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1428. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1429. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1430. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1431. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1432. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1433. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1434. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1435. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1436. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1437. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1438. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1439. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1440. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1441. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1442. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1443. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1444. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1445. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1446. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1447. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1448. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1449. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1450. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1451. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1452. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1453. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1454. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1455. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1456. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1457. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1458. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1459. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1460. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1461. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1462. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1463. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1464. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1465. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1466. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1467. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1468. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1469. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1470. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1471. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1472. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1473. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1474. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1475. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1476. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1477. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1478. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1479. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1480. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1481. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1482. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1483. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1484. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1485. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1486. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1487. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1488. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1489. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1490. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1491. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1492. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1493. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1494. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1495. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1496. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1497. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1498. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1499. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1500. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1501. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1502. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1503. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1504. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1505. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1506. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1507. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1508. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1509. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1510. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1511. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1512. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1513. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1514. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1515. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1516. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1517. ]
  1518. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1519. self.shell = FCShell(self, version=self.version)
  1520. self.shell._edit.set_model_data(self.myKeywords)
  1521. self.ui.code_editor.set_model_data(self.myKeywords)
  1522. self.shell.setWindowIcon(self.ui.app_icon)
  1523. self.shell.setWindowTitle("FlatCAM Shell")
  1524. self.shell.resize(*self.defaults["global_shell_shape"])
  1525. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1526. self.shell.append_output("(Type help to get started)\n\n")
  1527. self.init_tcl()
  1528. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1529. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1530. self.ui.shell_dock.setWidget(self.shell)
  1531. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1532. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1533. QtWidgets.QDockWidget.DockWidgetFloatable |
  1534. QtWidgets.QDockWidget.DockWidgetClosable)
  1535. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1536. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1537. if self.defaults["global_shell_at_startup"]:
  1538. self.ui.shell_dock.show()
  1539. else:
  1540. self.ui.shell_dock.hide()
  1541. # ###################### ##
  1542. # # ## Tools and Plugins # ##
  1543. # ###################### ##
  1544. self.dblsidedtool = None
  1545. self.measurement_tool = None
  1546. self.panelize_tool = None
  1547. self.film_tool = None
  1548. self.paste_tool = None
  1549. self.calculator_tool = None
  1550. self.sub_tool = None
  1551. self.move_tool = None
  1552. self.cutout_tool = None
  1553. self.ncclear_tool = None
  1554. self.paint_tool = None
  1555. self.transform_tool = None
  1556. self.properties_tool = None
  1557. self.pdf_tool = None
  1558. self.image_tool = None
  1559. self.pcb_wizard_tool = None
  1560. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1561. self.install_tools()
  1562. # # ## System Font Parsing # ##
  1563. # self.f_parse = ParseFont(self)
  1564. # self.parse_system_fonts()
  1565. # test if the program was started with a script as parameter
  1566. if self.cmd_line_shellfile:
  1567. try:
  1568. with open(self.cmd_line_shellfile, "r") as myfile:
  1569. cmd_line_shellfile_text = myfile.read()
  1570. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1571. except Exception as ext:
  1572. print("ERROR: ", ext)
  1573. sys.exit(2)
  1574. # ######################## ##
  1575. # # ## Check for updates ## ##
  1576. # ######################## ##
  1577. # Separate thread (Not worker)
  1578. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1579. if (self.beta is False or self.beta is None) and \
  1580. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1581. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1582. self.thr2 = QtCore.QThread()
  1583. self.worker_task.emit({'fcn': self.version_check,
  1584. 'params': []})
  1585. self.thr2.start(QtCore.QThread.LowPriority)
  1586. # ################################# ##
  1587. # # ## Variables for global usage ## ##
  1588. # ################################# ##
  1589. # coordinates for relative position display
  1590. self.rel_point1 = (0, 0)
  1591. self.rel_point2 = (0, 0)
  1592. # variable to store coordinates
  1593. self.pos = (0, 0)
  1594. self.pos_jump = (0, 0)
  1595. # decide if we have a double click or single click
  1596. self.doubleclick = False
  1597. # variable to store if a command is active (then the var is not None) and which one it is
  1598. self.command_active = None
  1599. # variable to store the status of moving selection action
  1600. # None value means that it's not an selection action
  1601. # True value = a selection from left to right
  1602. # False value = a selection from right to left
  1603. self.selection_type = None
  1604. # List to store the objects that are currently loaded in FlatCAM
  1605. # This list is updated on each object creation or object delete
  1606. self.all_objects_list = []
  1607. # List to store the objects that are selected
  1608. self.sel_objects_list = []
  1609. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1610. self.key_modifiers = None
  1611. # Variable to hold the status of the axis
  1612. self.toggle_axis = True
  1613. # Variable to store the status of the fullscreen event
  1614. self.toggle_fscreen = False
  1615. # Variable to store the status of the code editor
  1616. self.toggle_codeeditor = False
  1617. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1618. self.click_noproject = False
  1619. self.cursor = None
  1620. # Variable to store the GCODE that was edited
  1621. self.gcode_edited = ""
  1622. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1623. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1624. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1625. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1626. ]
  1627. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1628. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1629. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1630. 'mpf'
  1631. ]
  1632. self.svg_list = ['svg']
  1633. self.dxf_list = ['dxf']
  1634. self.pdf_list = ['pdf']
  1635. self.prj_list = ['flatprj']
  1636. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1637. # flag for polygons not cleared
  1638. self.poly_not_cleared = False
  1639. # VisPy visuals
  1640. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1641. self.isHovering = False
  1642. self.notHovering = True
  1643. # # ## Save defaults to factory_defaults.FlatConfig file # ##
  1644. # # ## It's done only once after install ########### ##
  1645. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1646. fac_def_from_file = factory_file.read()
  1647. factory_defaults = json.loads(fac_def_from_file)
  1648. # if the file contain an empty dictionary then save the factory defaults into the file
  1649. if not factory_defaults:
  1650. self.save_factory_defaults(silent=False)
  1651. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1652. initial_lay = 'compact'
  1653. self.on_layout(lay=initial_lay)
  1654. # Set the combobox in Preferences to the current layout
  1655. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1656. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1657. factory_file.close()
  1658. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1659. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1660. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1661. # Post-GUI initialization: Experimental attempt
  1662. # to perform unit tests on the GUI.
  1663. # if post_gui is not None:
  1664. # post_gui(self)
  1665. App.log.debug("END of constructor. Releasing control.")
  1666. # accept a project file as command line parameter
  1667. # the path/file_name must be enclosed in quotes if it contain spaces
  1668. for argument in App.args:
  1669. if '.FlatPrj' in argument:
  1670. try:
  1671. project_name = str(argument)
  1672. if project_name == "":
  1673. self.inform.emit(_("Open cancelled."))
  1674. else:
  1675. # self.open_project(project_name)
  1676. run_from_arg = True
  1677. self.worker_task.emit({'fcn': self.open_project,
  1678. 'params': [project_name, run_from_arg]})
  1679. except Exception as e:
  1680. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1681. if '.FlatConfig' in argument:
  1682. try:
  1683. file_name = str(argument)
  1684. if file_name == "":
  1685. self.inform.emit(_("Open Config file failed."))
  1686. else:
  1687. # run_from_arg = True
  1688. # self.worker_task.emit({'fcn': self.open_config_file,
  1689. # 'params': [file_name, run_from_arg]})
  1690. self.open_config_file(file_name, run_from_arg=True)
  1691. except Exception as e:
  1692. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1693. if '.FlatScript' in argument:
  1694. try:
  1695. file_name = str(argument)
  1696. if file_name == "":
  1697. self.inform.emit(_("Open Script file failed."))
  1698. else:
  1699. # run_from_arg = True
  1700. # self.worker_task.emit({'fcn': self.open_script_file,
  1701. # 'params': [file_name, run_from_arg]})
  1702. self.on_filerunscript(name=file_name)
  1703. except Exception as e:
  1704. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1705. def defaults_read_form(self):
  1706. for option in self.defaults_form_fields:
  1707. try:
  1708. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1709. except Exception as e:
  1710. log.debug("App.defaults_read_form() --> %s" % str(e))
  1711. def defaults_write_form(self, factor=None):
  1712. for option in self.defaults:
  1713. self.defaults_write_form_field(option, factor=factor)
  1714. # try:
  1715. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1716. # except KeyError:
  1717. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1718. # # TODO: Rethink this?
  1719. # pass
  1720. def defaults_write_form_field(self, field, factor=None):
  1721. try:
  1722. if factor is None:
  1723. self.defaults_form_fields[field].set_value(self.defaults[field])
  1724. else:
  1725. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1726. except KeyError:
  1727. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1728. # TODO: Rethink this?
  1729. pass
  1730. except AttributeError:
  1731. log.debug(field)
  1732. def clear_pool(self):
  1733. self.pool.close()
  1734. self.pool = Pool()
  1735. self.pool_recreated.emit(self.pool)
  1736. gc.collect()
  1737. # the order that the tools are installed is important as they can depend on each other install position
  1738. def install_tools(self):
  1739. self.dblsidedtool = DblSidedTool(self)
  1740. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1741. self.measurement_tool = Measurement(self)
  1742. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1743. self.panelize_tool = Panelize(self)
  1744. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1745. self.film_tool = Film(self)
  1746. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1747. self.paste_tool = SolderPaste(self)
  1748. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1749. self.calculator_tool = ToolCalculator(self)
  1750. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1751. self.sub_tool = ToolSub(self)
  1752. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
  1753. before=self.ui.menuedit_convert_sg2mg)
  1754. self.move_tool = ToolMove(self)
  1755. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1756. before=self.ui.menueditorigin)
  1757. self.cutout_tool = CutOut(self)
  1758. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1759. before=self.measurement_tool.menuAction)
  1760. self.ncclear_tool = NonCopperClear(self)
  1761. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1762. before=self.measurement_tool.menuAction, separator=True)
  1763. self.paint_tool = ToolPaint(self)
  1764. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1765. before=self.measurement_tool.menuAction, separator=True)
  1766. self.transform_tool = ToolTransform(self)
  1767. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1768. self.properties_tool = Properties(self)
  1769. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1770. self.pdf_tool = ToolPDF(self)
  1771. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1772. separator=True)
  1773. self.image_tool = ToolImage(self)
  1774. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1775. separator=True)
  1776. self.pcb_wizard_tool = PcbWizard(self)
  1777. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1778. self.log.debug("Tools are installed.")
  1779. def remove_tools(self):
  1780. for act in self.ui.menutool.actions():
  1781. self.ui.menutool.removeAction(act)
  1782. def init_tools(self):
  1783. log.debug("init_tools()")
  1784. # delete the data currently in the Tools Tab and the Tab itself
  1785. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1786. if widget is not None:
  1787. widget.deleteLater()
  1788. self.ui.notebook.removeTab(2)
  1789. # rebuild the Tools Tab
  1790. self.ui.tool_tab = QtWidgets.QWidget()
  1791. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1792. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1793. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1794. self.ui.tool_scroll_area = VerticalScrollArea()
  1795. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1796. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1797. # first remove all of them
  1798. self.remove_tools()
  1799. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1800. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1801. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1802. # third install all of them
  1803. self.install_tools()
  1804. self.log.debug("Tools are initialized.")
  1805. # def parse_system_fonts(self):
  1806. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1807. # 'params': []})
  1808. def connect_toolbar_signals(self):
  1809. # Toolbar
  1810. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1811. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1812. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1813. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1814. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1815. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1816. self.ui.replot_btn.triggered.connect(self.plot_all)
  1817. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1818. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1819. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1820. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1821. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1822. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1823. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1824. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1825. self.ui.delete_btn.triggered.connect(self.on_delete)
  1826. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1827. # Tools Toolbar Signals
  1828. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1829. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1830. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1831. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1832. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1833. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1834. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1835. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1836. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1837. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1838. def object2editor(self):
  1839. """
  1840. Send the current Geometry or Excellon object (if any) into the editor.
  1841. :return: None
  1842. """
  1843. self.report_usage("object2editor()")
  1844. edited_object = self.collection.get_active()
  1845. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  1846. isinstance(edited_object, FlatCAMExcellon):
  1847. pass
  1848. else:
  1849. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  1850. return
  1851. if isinstance(edited_object, FlatCAMGeometry):
  1852. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1853. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1854. if edited_object.multigeo is True:
  1855. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1856. if len(edited_tools) > 1:
  1857. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1858. "is not possible.\n"
  1859. "Edit only one geometry at a time."))
  1860. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1861. else:
  1862. self.geo_editor.edit_fcgeometry(edited_object)
  1863. # we set the notebook to hidden
  1864. self.ui.splitter.setSizes([0, 1])
  1865. # set call source to the Editor we go into
  1866. self.call_source = 'geo_editor'
  1867. elif isinstance(edited_object, FlatCAMExcellon):
  1868. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1869. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1870. self.exc_editor.edit_fcexcellon(edited_object)
  1871. # set call source to the Editor we go into
  1872. self.call_source = 'exc_editor'
  1873. if self.ui.splitter.sizes()[0] == 0:
  1874. self.ui.splitter.setSizes([1, 1])
  1875. elif isinstance(edited_object, FlatCAMGerber):
  1876. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1877. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1878. self.grb_editor.edit_fcgerber(edited_object)
  1879. # set call source to the Editor we go into
  1880. self.call_source = 'grb_editor'
  1881. if self.ui.splitter.sizes()[0] == 0:
  1882. self.ui.splitter.setSizes([1, 1])
  1883. # # make sure that we can't select another object while in Editor Mode:
  1884. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1885. self.ui.project_frame.setDisabled(True)
  1886. # delete any selection shape that might be active as they are not relevant in Editor
  1887. self.delete_selection_shape()
  1888. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1889. self.ui.plot_tab_area.protectTab(0)
  1890. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1891. self.should_we_save = True
  1892. def editor2object(self, cleanup=None):
  1893. """
  1894. Transfers the Geometry or Excellon from the editor to the current object.
  1895. :return: None
  1896. """
  1897. self.report_usage("editor2object()")
  1898. # do not update a geometry or excellon object unless it comes out of an editor
  1899. if self.call_source != 'app':
  1900. edited_obj = self.collection.get_active()
  1901. if cleanup is None:
  1902. msgbox = QtWidgets.QMessageBox()
  1903. msgbox.setText(_("Do you want to save the edited object?"))
  1904. msgbox.setWindowTitle(_("Close Editor"))
  1905. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1906. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1907. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1908. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1909. msgbox.setDefaultButton(bt_yes)
  1910. msgbox.exec_()
  1911. response = msgbox.clickedButton()
  1912. if response == bt_yes:
  1913. # clean the Tools Tab
  1914. self.ui.tool_scroll_area.takeWidget()
  1915. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1916. self.ui.notebook.setTabText(2, "Tool")
  1917. if isinstance(edited_obj, FlatCAMGeometry):
  1918. obj_type = "Geometry"
  1919. if cleanup is None:
  1920. self.geo_editor.update_fcgeometry(edited_obj)
  1921. self.geo_editor.update_options(edited_obj)
  1922. self.geo_editor.deactivate()
  1923. # update the geo object options so it is including the bounding box values
  1924. try:
  1925. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1926. edited_obj.options['xmin'] = xmin
  1927. edited_obj.options['ymin'] = ymin
  1928. edited_obj.options['xmax'] = xmax
  1929. edited_obj.options['ymax'] = ymax
  1930. except AttributeError as e:
  1931. self.inform.emit(_("[WARNING] Object empty after edit."))
  1932. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1933. elif isinstance(edited_obj, FlatCAMGerber):
  1934. obj_type = "Gerber"
  1935. if cleanup is None:
  1936. self.grb_editor.update_fcgerber()
  1937. self.grb_editor.update_options(edited_obj)
  1938. self.grb_editor.deactivate_grb_editor()
  1939. # delete the old object (the source object) if it was an empty one
  1940. if len(edited_obj.solid_geometry) == 0:
  1941. old_name = edited_obj.options['name']
  1942. self.collection.set_active(old_name)
  1943. self.collection.delete_active()
  1944. elif isinstance(edited_obj, FlatCAMExcellon):
  1945. obj_type = "Excellon"
  1946. if cleanup is None:
  1947. self.exc_editor.update_fcexcellon(edited_obj)
  1948. self.exc_editor.update_options(edited_obj)
  1949. self.exc_editor.deactivate()
  1950. else:
  1951. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1952. return
  1953. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1954. elif response == bt_no:
  1955. # clean the Tools Tab
  1956. self.ui.tool_scroll_area.takeWidget()
  1957. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1958. self.ui.notebook.setTabText(2, "Tool")
  1959. if isinstance(edited_obj, FlatCAMGeometry):
  1960. self.geo_editor.deactivate()
  1961. elif isinstance(edited_obj, FlatCAMGerber):
  1962. self.grb_editor.deactivate_grb_editor()
  1963. elif isinstance(edited_obj, FlatCAMExcellon):
  1964. self.exc_editor.deactivate()
  1965. # set focus on the project tab
  1966. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  1967. else:
  1968. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1969. return
  1970. elif response == bt_cancel:
  1971. return
  1972. else:
  1973. if isinstance(edited_obj, FlatCAMGeometry):
  1974. self.geo_editor.deactivate()
  1975. elif isinstance(edited_obj, FlatCAMGerber):
  1976. self.grb_editor.deactivate_grb_editor()
  1977. elif isinstance(edited_obj, FlatCAMExcellon):
  1978. self.exc_editor.deactivate()
  1979. else:
  1980. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1981. return
  1982. # if notebook is hidden we show it
  1983. if self.ui.splitter.sizes()[0] == 0:
  1984. self.ui.splitter.setSizes([1, 1])
  1985. # restore the call_source to app
  1986. self.call_source = 'app'
  1987. edited_obj.plot()
  1988. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1989. self.ui.plot_tab_area.protectTab(0)
  1990. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1991. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1992. self.ui.project_frame.setDisabled(False)
  1993. def get_last_folder(self):
  1994. return self.defaults["global_last_folder"]
  1995. def get_last_save_folder(self):
  1996. loc = self.defaults["global_last_save_folder"]
  1997. if loc is None:
  1998. loc = self.defaults["global_last_folder"]
  1999. if loc is None:
  2000. loc = os.path.dirname(__file__)
  2001. return loc
  2002. def report_usage(self, resource):
  2003. """
  2004. Increments usage counter for the given resource
  2005. in self.defaults['global_stats'].
  2006. :param resource: Name of the resource.
  2007. :return: None
  2008. """
  2009. if resource in self.defaults['global_stats']:
  2010. self.defaults['global_stats'][resource] += 1
  2011. else:
  2012. self.defaults['global_stats'][resource] = 1
  2013. def init_tcl(self):
  2014. if hasattr(self, 'tcl'):
  2015. # self.tcl = None
  2016. # TODO we need to clean non default variables and procedures here
  2017. # new object cannot be used here as it will not remember values created for next passes,
  2018. # because tcl was execudted in old instance of TCL
  2019. pass
  2020. else:
  2021. self.tcl = tk.Tcl()
  2022. self.setup_shell()
  2023. self.log.debug("TCL Shell has been initialized.")
  2024. # TODO: This shouldn't be here.
  2025. class TclErrorException(Exception):
  2026. """
  2027. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2028. """
  2029. pass
  2030. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2031. """
  2032. Shows a message on the FlatCAM Shell
  2033. :param msg: Message to display.
  2034. :param show: Opens the shell.
  2035. :param error: Shows the message as an error.
  2036. :param warning: Shows the message as an warning.
  2037. :param warning: Shows the message as an success.
  2038. :param selected: Indicate that something was selected on canvas
  2039. :return: None
  2040. """
  2041. if show:
  2042. self.ui.shell_dock.show()
  2043. try:
  2044. if error:
  2045. self.shell.append_error(msg + "\n")
  2046. elif warning:
  2047. self.shell.append_warning(msg + "\n")
  2048. elif success:
  2049. self.shell.append_success(msg + "\n")
  2050. elif selected:
  2051. self.shell.append_selected(msg + "\n")
  2052. else:
  2053. self.shell.append_output(msg + "\n")
  2054. except AttributeError:
  2055. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2056. def raise_tcl_unknown_error(self, unknownException):
  2057. """
  2058. Raise exception if is different type than TclErrorException
  2059. this is here mainly to show unknown errors inside TCL shell console.
  2060. :param unknownException:
  2061. :return:
  2062. """
  2063. if not isinstance(unknownException, self.TclErrorException):
  2064. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2065. else:
  2066. raise unknownException
  2067. def display_tcl_error(self, error, error_info=None):
  2068. """
  2069. Escape bracket [ with '\' otherwise there is error
  2070. "ERROR: missing close-bracket" instead of real error
  2071. :param error: it may be text or exception
  2072. :param error_info: Some informations about the error
  2073. :return: None
  2074. """
  2075. if isinstance(error, Exception):
  2076. exc_type, exc_value, exc_traceback = error_info
  2077. if not isinstance(error, self.TclErrorException):
  2078. show_trace = 1
  2079. else:
  2080. show_trace = int(self.defaults['global_verbose_error_level'])
  2081. if show_trace > 0:
  2082. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2083. trc_formated = []
  2084. for a in reversed(trc):
  2085. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2086. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2087. else:
  2088. text = "%s" % error
  2089. else:
  2090. text = error
  2091. text = text.replace('[', '\\[').replace('"', '\\"')
  2092. self.tcl.eval('return -code error "%s"' % text)
  2093. def raise_tcl_error(self, text):
  2094. """
  2095. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2096. :param text: text of error
  2097. :return: raise exception
  2098. """
  2099. self.display_tcl_error(text)
  2100. raise self.TclErrorException(text)
  2101. def exec_command(self, text):
  2102. """
  2103. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2104. Also handles execution in separated threads
  2105. :param text:
  2106. :return: output if there was any
  2107. """
  2108. self.report_usage('exec_command')
  2109. result = self.exec_command_test(text, False)
  2110. # MS: added this method call so the geometry is updated once the TCL command is executed
  2111. self.plot_all()
  2112. return result
  2113. def exec_command_test(self, text, reraise=True):
  2114. """
  2115. Same as exec_command(...) with additional control over exceptions.
  2116. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2117. :param text: Input command
  2118. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2119. :return: Output from the command
  2120. """
  2121. text = str(text)
  2122. try:
  2123. self.shell.open_proccessing() # Disables input box.
  2124. result = self.tcl.eval(str(text))
  2125. if result != 'None':
  2126. self.shell.append_output(result + '\n')
  2127. except tk.TclError as e:
  2128. # This will display more precise answer if something in TCL shell fails
  2129. result = self.tcl.eval("set errorInfo")
  2130. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2131. self.shell.append_error('ERROR: ' + result + '\n')
  2132. # Show error in console and just return or in test raise exception
  2133. if reraise:
  2134. raise e
  2135. finally:
  2136. self.shell.close_proccessing()
  2137. pass
  2138. return result
  2139. # """
  2140. # Code below is unsused. Saved for later.
  2141. # """
  2142. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2143. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2144. # self.log.debug(parts)
  2145. # try:
  2146. # if parts[0] not in commands:
  2147. # self.shell.append_error("Unknown command\n")
  2148. # return
  2149. #
  2150. # #import inspect
  2151. # #inspect.getargspec(someMethod)
  2152. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2153. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2154. # self.shell.append_error(
  2155. # "Command %s takes %d arguments. %d given.\n" %
  2156. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2157. # )
  2158. # return
  2159. #
  2160. # cmdfcn = commands[parts[0]]["fcn"]
  2161. # cmdconv = commands[parts[0]]["converters"]
  2162. # if len(parts) - 1 > 0:
  2163. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2164. # else:
  2165. # retval = cmdfcn()
  2166. # retfcn = commands[parts[0]]["retfcn"]
  2167. # if retval and retfcn(retval):
  2168. # self.shell.append_output(retfcn(retval) + "\n")
  2169. #
  2170. # except Exception as e:
  2171. # #self.shell.append_error(''.join(traceback.format_exc()))
  2172. # #self.shell.append_error("?\n")
  2173. # self.shell.append_error(str(e) + "\n")
  2174. def info(self, msg):
  2175. """
  2176. Informs the user. Normally on the status bar, optionally
  2177. also on the shell.
  2178. :param msg: Text to write.
  2179. :return: None
  2180. """
  2181. # Type of message in brackets at the beginning of the message.
  2182. match = re.search("\[([^\]]+)\](.*)", msg)
  2183. if match:
  2184. level = match.group(1)
  2185. msg_ = match.group(2)
  2186. self.ui.fcinfo.set_status(str(msg_), level=level)
  2187. if level.lower() == "error":
  2188. self.shell_message(msg, error=True, show=True)
  2189. elif level.lower() == "warning":
  2190. self.shell_message(msg, warning=True, show=True)
  2191. elif level.lower() == "error_notcl":
  2192. self.shell_message(msg, error=True, show=False)
  2193. elif level.lower() == "warning_notcl":
  2194. self.shell_message(msg, warning=True, show=False)
  2195. elif level.lower() == "success":
  2196. self.shell_message(msg, success=True, show=False)
  2197. elif level.lower() == "selected":
  2198. self.shell_message(msg, selected=True, show=False)
  2199. else:
  2200. self.shell_message(msg, show=False)
  2201. else:
  2202. self.ui.fcinfo.set_status(str(msg), level="info")
  2203. # make sure that if the message is to clear the infobar with a space
  2204. # is not printed over and over on the shell
  2205. if msg != '':
  2206. self.shell_message(msg)
  2207. def restore_toolbar_view(self):
  2208. tb = self.defaults["global_toolbar_view"]
  2209. if tb & 1:
  2210. self.ui.toolbarfile.setVisible(True)
  2211. else:
  2212. self.ui.toolbarfile.setVisible(False)
  2213. if tb & 2:
  2214. self.ui.toolbargeo.setVisible(True)
  2215. else:
  2216. self.ui.toolbargeo.setVisible(False)
  2217. if tb & 4:
  2218. self.ui.toolbarview.setVisible(True)
  2219. else:
  2220. self.ui.toolbarview.setVisible(False)
  2221. if tb & 8:
  2222. self.ui.toolbartools.setVisible(True)
  2223. else:
  2224. self.ui.toolbartools.setVisible(False)
  2225. if tb & 16:
  2226. self.ui.exc_edit_toolbar.setVisible(True)
  2227. else:
  2228. self.ui.exc_edit_toolbar.setVisible(False)
  2229. if tb & 32:
  2230. self.ui.geo_edit_toolbar.setVisible(True)
  2231. else:
  2232. self.ui.geo_edit_toolbar.setVisible(False)
  2233. if tb & 64:
  2234. self.ui.grb_edit_toolbar.setVisible(True)
  2235. else:
  2236. self.ui.grb_edit_toolbar.setVisible(False)
  2237. if tb & 128:
  2238. self.ui.snap_toolbar.setVisible(True)
  2239. else:
  2240. self.ui.snap_toolbar.setVisible(False)
  2241. if tb & 256:
  2242. self.ui.toolbarshell.setVisible(True)
  2243. else:
  2244. self.ui.toolbarshell.setVisible(False)
  2245. def load_defaults(self, filename):
  2246. """
  2247. Loads the aplication's default settings from current_defaults.FlatConfig into
  2248. ``self.defaults``.
  2249. :return: None
  2250. """
  2251. try:
  2252. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2253. options = f.read()
  2254. f.close()
  2255. except IOError:
  2256. self.log.error("Could not load defaults file.")
  2257. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2258. # in case the defaults file can't be loaded, show all toolbars
  2259. self.defaults["global_toolbar_view"] = 511
  2260. return
  2261. try:
  2262. defaults = json.loads(options)
  2263. except:
  2264. # in case the defaults file can't be loaded, show all toolbars
  2265. self.defaults["global_toolbar_view"] = 511
  2266. e = sys.exc_info()[0]
  2267. App.log.error(str(e))
  2268. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2269. return
  2270. self.defaults.update(defaults)
  2271. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2272. # restore the toolbar view
  2273. self.restore_toolbar_view()
  2274. def on_import_preferences(self):
  2275. """
  2276. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2277. ``self.defaults``.
  2278. :return: None
  2279. """
  2280. self.report_usage("on_import_preferences")
  2281. App.log.debug("on_import_preferences()")
  2282. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2283. try:
  2284. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2285. directory=self.data_path,
  2286. filter=filter_)
  2287. except TypeError:
  2288. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2289. filter=filter_)
  2290. filename = str(filename)
  2291. if filename == "":
  2292. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2293. else:
  2294. try:
  2295. f = open(filename)
  2296. options = f.read()
  2297. f.close()
  2298. except IOError:
  2299. self.log.error("Could not load defaults file.")
  2300. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2301. return
  2302. try:
  2303. defaults_from_file = json.loads(options)
  2304. except Exception as e:
  2305. e = sys.exc_info()[0]
  2306. App.log.error(str(e))
  2307. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2308. return
  2309. self.defaults.update(defaults_from_file)
  2310. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2311. def on_export_preferences(self):
  2312. self.report_usage("on_export_preferences")
  2313. App.log.debug("on_export_preferences()")
  2314. defaults_file_content = None
  2315. self.date = str(datetime.today()).rpartition('.')[0]
  2316. self.date = ''.join(c for c in self.date if c not in ':-')
  2317. self.date = self.date.replace(' ', '_')
  2318. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2319. try:
  2320. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2321. caption=_("Export FlatCAM Preferences"),
  2322. directory=self.data_path + '/preferences_' + self.date,
  2323. filter=filter
  2324. )
  2325. except TypeError:
  2326. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2327. filter=filter)
  2328. filename = str(filename)
  2329. defaults_from_file = {}
  2330. if filename == "":
  2331. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2332. return
  2333. else:
  2334. try:
  2335. f = open(filename, 'w')
  2336. defaults_file_content = f.read()
  2337. f.close()
  2338. except IOError:
  2339. App.log.debug('Creating a new preferences file ...')
  2340. f = open(filename, 'w')
  2341. json.dump({}, f)
  2342. f.close()
  2343. except:
  2344. e = sys.exc_info()[0]
  2345. App.log.error("Could not load defaults file.")
  2346. App.log.error(str(e))
  2347. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2348. return
  2349. try:
  2350. defaults_from_file = json.loads(defaults_file_content)
  2351. except:
  2352. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2353. # Update options
  2354. self.defaults_read_form()
  2355. defaults_from_file.update(self.defaults)
  2356. self.propagate_defaults(silent=True)
  2357. # Save update options
  2358. try:
  2359. f = open(filename, "w")
  2360. json.dump(defaults_from_file, f)
  2361. f.close()
  2362. except:
  2363. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2364. return
  2365. if self.defaults["global_open_style"] is False:
  2366. self.file_opened.emit("preferences", filename)
  2367. self.file_saved.emit("preferences", filename)
  2368. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2369. def on_preferences_open_folder(self):
  2370. self.report_usage("on_preferences_open_folder()")
  2371. if sys.platform == 'win32':
  2372. subprocess.Popen('explorer %s' % self.data_path)
  2373. elif sys.platform == 'darwin':
  2374. os.system('open "%s"' % self.data_path)
  2375. else:
  2376. subprocess.Popen(['xdg-open', self.data_path])
  2377. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2378. def save_geometry(self, x, y, width, height, notebook_width):
  2379. self.defaults["global_def_win_x"] = x
  2380. self.defaults["global_def_win_y"] = y
  2381. self.defaults["global_def_win_w"] = width
  2382. self.defaults["global_def_win_h"] = height
  2383. self.defaults["global_def_notebook_width"] = notebook_width
  2384. self.save_defaults()
  2385. def message_dialog(self, title, message, kind="info"):
  2386. icon = {"info": QtWidgets.QMessageBox.Information,
  2387. "warning": QtWidgets.QMessageBox.Warning,
  2388. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2389. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2390. dlg.setText(message)
  2391. dlg.exec_()
  2392. def register_recent(self, kind, filename):
  2393. self.log.debug("register_recent()")
  2394. self.log.debug(" %s" % kind)
  2395. self.log.debug(" %s" % filename)
  2396. record = {'kind': str(kind), 'filename': str(filename)}
  2397. if record in self.recent:
  2398. return
  2399. self.recent.insert(0, record)
  2400. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2401. self.recent.pop()
  2402. try:
  2403. f = open(self.data_path + '/recent.json', 'w')
  2404. except IOError:
  2405. App.log.error("Failed to open recent items file for writing.")
  2406. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2407. return
  2408. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2409. f.close()
  2410. # Re-build the recent items menu
  2411. self.setup_recent_items()
  2412. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2413. """
  2414. Creates a new specialized FlatCAMObj and attaches it to the application,
  2415. this is, updates the GUI accordingly, any other records and plots it.
  2416. This method is thread-safe.
  2417. Notes:
  2418. * If the name is in use, the self.collection will modify it
  2419. when appending it to the collection. There is no need to handle
  2420. name conflicts here.
  2421. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2422. :type kind: str
  2423. :param name: Name for the object.
  2424. :type name: str
  2425. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2426. The function is called with 2 parameters: the new object and the App instance.
  2427. :type initialize: function
  2428. :return: None
  2429. :rtype: None
  2430. """
  2431. App.log.debug("new_object()")
  2432. obj_plot = plot
  2433. obj_autoselected = autoselected
  2434. t0 = time.time() # Debug
  2435. # ## Create object
  2436. classdict = {
  2437. "gerber": FlatCAMGerber,
  2438. "excellon": FlatCAMExcellon,
  2439. "cncjob": FlatCAMCNCjob,
  2440. "geometry": FlatCAMGeometry
  2441. }
  2442. App.log.debug("Calling object constructor...")
  2443. obj = classdict[kind](name)
  2444. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2445. # Set options from "Project options" form
  2446. self.options_read_form()
  2447. # IMPORTANT
  2448. # The key names in defaults and options dictionary's are not random:
  2449. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2450. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2451. # the options from project options form into the self.options. After that, below, depending on the type of
  2452. # object that is created, it will strip the name of the object and the underline (if the original key was
  2453. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2454. # "toolchange"
  2455. for option in self.options:
  2456. if option.find(kind + "_") == 0:
  2457. oname = option[len(kind) + 1:]
  2458. obj.options[oname] = self.options[option]
  2459. obj.isHovering = False
  2460. obj.notHovering = True
  2461. # Initialize as per user request
  2462. # User must take care to implement initialize
  2463. # in a thread-safe way as is is likely that we
  2464. # have been invoked in a separate thread.
  2465. t1 = time.time()
  2466. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2467. try:
  2468. return_value = initialize(obj, self)
  2469. except Exception as e:
  2470. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2471. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2472. msg += traceback.format_exc()
  2473. self.inform.emit(msg)
  2474. # if str(e) == "Empty Geometry":
  2475. # self.inform.emit("[ERROR_NOTCL] )
  2476. # else:
  2477. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2478. return "fail"
  2479. t2 = time.time()
  2480. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2481. if return_value == 'fail':
  2482. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2483. return "fail"
  2484. # Check units and convert if necessary
  2485. # This condition CAN be true because initialize() can change obj.units
  2486. if self.options["units"].upper() != obj.units.upper():
  2487. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2488. obj.convert_units(self.options["units"])
  2489. t3 = time.time()
  2490. self.log.debug("%f seconds converting units." % (t3 - t2))
  2491. # Create the bounding box for the object and then add the results to the obj.options
  2492. try:
  2493. xmin, ymin, xmax, ymax = obj.bounds()
  2494. obj.options['xmin'] = xmin
  2495. obj.options['ymin'] = ymin
  2496. obj.options['xmax'] = xmax
  2497. obj.options['ymax'] = ymax
  2498. except:
  2499. log.warning("The object has no bounds properties.")
  2500. # don't plot objects with no bounds, there is nothing to plot
  2501. self.plot = False
  2502. pass
  2503. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2504. # Move the object to the main thread and let the app know that it is available.
  2505. obj.moveToThread(self.main_thread)
  2506. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2507. return obj
  2508. def new_excellon_object(self):
  2509. self.report_usage("new_excellon_object()")
  2510. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2511. def new_geometry_object(self):
  2512. self.report_usage("new_geometry_object()")
  2513. def initialize(obj, self):
  2514. obj.multitool = False
  2515. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2516. def new_gerber_object(self):
  2517. self.report_usage("new_gerber_object()")
  2518. def initialize(grb_obj, self):
  2519. grb_obj.multitool = False
  2520. grb_obj.source_file = []
  2521. grb_obj.multigeo = False
  2522. grb_obj.follow = False
  2523. grb_obj.apertures = {}
  2524. grb_obj.solid_geometry = []
  2525. try:
  2526. grb_obj.options['xmin'] = 0
  2527. grb_obj.options['ymin'] = 0
  2528. grb_obj.options['xmax'] = 0
  2529. grb_obj.options['ymax'] = 0
  2530. except KeyError:
  2531. pass
  2532. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2533. def on_object_created(self, obj, plot, autoselect):
  2534. """
  2535. Event callback for object creation.
  2536. :param obj: The newly created FlatCAM object.
  2537. :return: None
  2538. """
  2539. t0 = time.time() # DEBUG
  2540. self.log.debug("on_object_created()")
  2541. # The Collection might change the name if there is a collision
  2542. self.collection.append(obj)
  2543. # after adding the object to the collection always update the list of objects that are in the collection
  2544. self.all_objects_list = self.collection.get_list()
  2545. # self.inform.emit('[selected] %s created & selected: %s' %
  2546. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2547. if obj.kind == 'gerber':
  2548. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2549. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2550. elif obj.kind == 'excellon':
  2551. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2552. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2553. elif obj.kind == 'cncjob':
  2554. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2555. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2556. elif obj.kind == 'geometry':
  2557. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2558. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2559. # update the SHELL auto-completer model with the name of the new object
  2560. self.myKeywords.append(obj.options['name'])
  2561. self.shell._edit.set_model_data(self.myKeywords)
  2562. self.ui.code_editor.set_model_data(self.myKeywords)
  2563. if autoselect:
  2564. # select the just opened object but deselect the previous ones
  2565. self.collection.set_all_inactive()
  2566. self.collection.set_active(obj.options["name"])
  2567. # here it is done the object plotting
  2568. def worker_task(t_obj):
  2569. with self.proc_container.new("Plotting"):
  2570. if isinstance(t_obj, FlatCAMCNCjob):
  2571. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2572. else:
  2573. t_obj.plot()
  2574. t1 = time.time() # DEBUG
  2575. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2576. self.object_plotted.emit(t_obj)
  2577. # Send to worker
  2578. # self.worker.add_task(worker_task, [self])
  2579. if plot is True:
  2580. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2581. def on_object_changed(self, obj):
  2582. # update the bounding box data from obj.options
  2583. xmin, ymin, xmax, ymax = obj.bounds()
  2584. obj.options['xmin'] = xmin
  2585. obj.options['ymin'] = ymin
  2586. obj.options['xmax'] = xmax
  2587. obj.options['ymax'] = ymax
  2588. log.debug("Object changed, updating the bounding box data on self.options")
  2589. # delete the old selection shape
  2590. self.delete_selection_shape()
  2591. self.should_we_save = True
  2592. def on_object_plotted(self, obj):
  2593. self.on_zoom_fit(None)
  2594. def options_read_form(self):
  2595. for option in self.options_form_fields:
  2596. self.options[option] = self.options_form_fields[option].get_value()
  2597. def options_write_form(self):
  2598. for option in self.options:
  2599. self.options_write_form_field(option)
  2600. def options_write_form_field(self, field):
  2601. try:
  2602. self.options_form_fields[field].set_value(self.options[field])
  2603. except KeyError:
  2604. # Changed from error to debug. This allows to have data stored
  2605. # which is not user-editable.
  2606. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2607. pass
  2608. def on_about(self):
  2609. """
  2610. Displays the "about" dialog.
  2611. :return: None
  2612. """
  2613. self.report_usage("on_about")
  2614. version = self.version
  2615. version_date = self.version_date
  2616. beta = self.beta
  2617. class AboutDialog(QtWidgets.QDialog):
  2618. def __init__(self, parent=None):
  2619. QtWidgets.QDialog.__init__(self, parent)
  2620. # Icon and title
  2621. self.setWindowIcon(parent.app_icon)
  2622. self.setWindowTitle("FlatCAM")
  2623. layout1 = QtWidgets.QVBoxLayout()
  2624. self.setLayout(layout1)
  2625. layout2 = QtWidgets.QHBoxLayout()
  2626. layout1.addLayout(layout2)
  2627. logo = QtWidgets.QLabel()
  2628. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2629. layout2.addWidget(logo, stretch=0)
  2630. title = QtWidgets.QLabel(
  2631. _(
  2632. "<font size=8><B>FlatCAM</B></font><BR>"
  2633. "Version {version} {beta} ({date}) - {arch} <BR>"
  2634. "<BR>"
  2635. "2D Computer-Aided Printed Circuit Board<BR>"
  2636. "Manufacturing.<BR>"
  2637. "<BR>"
  2638. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2639. "<BR>"
  2640. "<B> Main Contributors:</B><BR>"
  2641. "Denis Hayrullin<BR>"
  2642. "Kamil Sopko<BR>"
  2643. "Marius Stanciu<BR>"
  2644. "Matthieu Berthomé<BR>"
  2645. "and many others found "
  2646. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2647. "<BR>"
  2648. "Development is done "
  2649. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2650. "DOWNLOAD area "
  2651. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2652. ""
  2653. ).format(version=version,
  2654. beta=('BETA' if beta else ''),
  2655. date=version_date,
  2656. arch=platform.architecture()[0])
  2657. )
  2658. title.setOpenExternalLinks(True)
  2659. layout2.addWidget(title, stretch=1)
  2660. layout3 = QtWidgets.QHBoxLayout()
  2661. layout1.addLayout(layout3)
  2662. layout3.addStretch()
  2663. okbtn = QtWidgets.QPushButton("Close")
  2664. layout3.addWidget(okbtn)
  2665. okbtn.clicked.connect(self.accept)
  2666. AboutDialog(self.ui).exec_()
  2667. def on_file_savedefaults(self):
  2668. """
  2669. Callback for menu item File->Save Defaults. Saves application default options
  2670. ``self.defaults`` to current_defaults.FlatConfig.
  2671. :return: None
  2672. """
  2673. self.save_defaults()
  2674. # def on_app_exit(self):
  2675. # self.report_usage("on_app_exit()")
  2676. #
  2677. # if self.collection.get_list():
  2678. # msgbox = QtWidgets.QMessageBox()
  2679. # # msgbox.setText("<B>Save changes ...</B>")
  2680. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2681. # "\n"
  2682. # "Do you want to Save the project?")
  2683. # msgbox.setWindowTitle("Save changes")
  2684. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2685. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2686. # QtWidgets.QMessageBox.Cancel)
  2687. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2688. #
  2689. # response = msgbox.exec_()
  2690. #
  2691. # if response == QtWidgets.QMessageBox.Yes:
  2692. # self.on_file_saveprojectas(thread=False)
  2693. # elif response == QtWidgets.QMessageBox.Cancel:
  2694. # return
  2695. # self.save_defaults()
  2696. # else:
  2697. # self.save_defaults()
  2698. # log.debug("Application defaults saved ... Exit event.")
  2699. # QtWidgets.qApp.quit()
  2700. def save_defaults(self, silent=False):
  2701. """
  2702. Saves application default options
  2703. ``self.defaults`` to current_defaults.FlatConfig.
  2704. :return: None
  2705. """
  2706. self.report_usage("save_defaults")
  2707. # Read options from file
  2708. try:
  2709. f = open(self.data_path + "/current_defaults.FlatConfig")
  2710. defaults_file_content = f.read()
  2711. f.close()
  2712. except:
  2713. e = sys.exc_info()[0]
  2714. App.log.error("Could not load defaults file.")
  2715. App.log.error(str(e))
  2716. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2717. return
  2718. try:
  2719. defaults = json.loads(defaults_file_content)
  2720. except:
  2721. e = sys.exc_info()[0]
  2722. App.log.error("Failed to parse defaults file.")
  2723. App.log.error(str(e))
  2724. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2725. return
  2726. # Update options
  2727. self.defaults_read_form()
  2728. defaults.update(self.defaults)
  2729. self.propagate_defaults(silent=True)
  2730. # Save the toolbar view
  2731. tb_status = 0
  2732. if self.ui.toolbarfile.isVisible():
  2733. tb_status += 1
  2734. if self.ui.toolbargeo.isVisible():
  2735. tb_status += 2
  2736. if self.ui.toolbarview.isVisible():
  2737. tb_status += 4
  2738. if self.ui.toolbartools.isVisible():
  2739. tb_status += 8
  2740. if self.ui.exc_edit_toolbar.isVisible():
  2741. tb_status += 16
  2742. if self.ui.geo_edit_toolbar.isVisible():
  2743. tb_status += 32
  2744. if self.ui.grb_edit_toolbar.isVisible():
  2745. tb_status += 64
  2746. if self.ui.snap_toolbar.isVisible():
  2747. tb_status += 128
  2748. if self.ui.toolbarshell.isVisible():
  2749. tb_status += 256
  2750. self.defaults["global_toolbar_view"] = tb_status
  2751. # Save update options
  2752. try:
  2753. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2754. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2755. f.close()
  2756. except:
  2757. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2758. return
  2759. if not silent:
  2760. self.inform.emit(_("[success] Defaults saved."))
  2761. def save_factory_defaults(self, silent=False):
  2762. """
  2763. Saves application factory default options
  2764. ``self.defaults`` to factory_defaults.FlatConfig.
  2765. It's a one time job done just after the first install.
  2766. :return: None
  2767. """
  2768. self.report_usage("save_factory_defaults")
  2769. # Read options from file
  2770. try:
  2771. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2772. factory_defaults_file_content = f_f_def.read()
  2773. f_f_def.close()
  2774. except:
  2775. e = sys.exc_info()[0]
  2776. App.log.error("Could not load factory defaults file.")
  2777. App.log.error(str(e))
  2778. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2779. return
  2780. try:
  2781. factory_defaults = json.loads(factory_defaults_file_content)
  2782. except:
  2783. e = sys.exc_info()[0]
  2784. App.log.error("Failed to parse factory defaults file.")
  2785. App.log.error(str(e))
  2786. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2787. return
  2788. # Update options
  2789. self.defaults_read_form()
  2790. factory_defaults.update(self.defaults)
  2791. self.propagate_defaults(silent=True)
  2792. # Save update options
  2793. try:
  2794. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2795. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2796. f_f_def_s.close()
  2797. except:
  2798. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2799. return
  2800. if silent is False:
  2801. self.inform.emit(_("Factory defaults saved."))
  2802. def final_save(self):
  2803. if self.save_in_progress:
  2804. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  2805. return
  2806. if self.should_we_save and self.collection.get_list():
  2807. msgbox = QtWidgets.QMessageBox()
  2808. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2809. "\n"
  2810. "Do you want to Save the project?"))
  2811. msgbox.setWindowTitle(_("Save changes"))
  2812. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2813. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2814. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2815. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2816. msgbox.setDefaultButton(bt_yes)
  2817. msgbox.exec_()
  2818. response = msgbox.clickedButton()
  2819. if response == bt_yes:
  2820. self.on_file_saveprojectas(thread=True, quit=True)
  2821. elif response == bt_no:
  2822. self.quit_application()
  2823. elif response == bt_cancel:
  2824. return
  2825. else:
  2826. self.quit_application()
  2827. def quit_application(self):
  2828. self.save_defaults()
  2829. log.debug("App.final_save() --> App Defaults saved.")
  2830. # save toolbar state to file
  2831. settings = QSettings("Open Source", "FlatCAM")
  2832. settings.setValue('saved_gui_state', self.ui.saveState())
  2833. settings.setValue('maximized_gui', self.ui.isMaximized())
  2834. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  2835. # This will write the setting to the platform specific storage.
  2836. del settings
  2837. log.debug("App.final_save() --> App UI state saved.")
  2838. QtWidgets.qApp.quit()
  2839. def on_toggle_shell(self):
  2840. """
  2841. toggle shell if is visible close it if closed open it
  2842. :return:
  2843. """
  2844. self.report_usage("on_toggle_shell()")
  2845. if self.ui.shell_dock.isVisible():
  2846. self.ui.shell_dock.hide()
  2847. else:
  2848. self.ui.shell_dock.show()
  2849. def on_edit_join(self, name=None):
  2850. """
  2851. Callback for Edit->Join. Joins the selected geometry objects into
  2852. a new one.
  2853. :return: None
  2854. """
  2855. self.report_usage("on_edit_join()")
  2856. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2857. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2858. tooldias = []
  2859. geo_type_list = []
  2860. objs = self.collection.get_selected()
  2861. for obj in objs:
  2862. geo_type_list.append(obj.multigeo)
  2863. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2864. if len(set(geo_type_list)) != 1:
  2865. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2866. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2867. "convert from one to another and retry joining \n"
  2868. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2869. "the result may not be what was expected. \n"
  2870. "Check the generated GCODE."))
  2871. return
  2872. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2873. if True in geo_type_list:
  2874. def initialize(obj, app):
  2875. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2876. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2877. for v in obj.tools.values():
  2878. v['data']['name'] = obj_name_multi
  2879. self.new_object("geometry", obj_name_multi, initialize)
  2880. else:
  2881. def initialize(obj, app):
  2882. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2883. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2884. for v in obj.tools.values():
  2885. v['data']['name'] = obj_name_single
  2886. self.new_object("geometry", obj_name_single, initialize)
  2887. self.should_we_save = True
  2888. def on_edit_join_exc(self):
  2889. """
  2890. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2891. a new one.
  2892. :return: None
  2893. """
  2894. self.report_usage("on_edit_join_exc()")
  2895. objs = self.collection.get_selected()
  2896. for obj in objs:
  2897. if not isinstance(obj, FlatCAMExcellon):
  2898. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2899. return
  2900. def initialize(obj, app):
  2901. FlatCAMExcellon.merge(objs, obj)
  2902. self.new_object("excellon", 'Combo_Excellon', initialize)
  2903. self.should_we_save = True
  2904. def on_edit_join_grb(self):
  2905. """
  2906. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2907. a new one.
  2908. :return: None
  2909. """
  2910. self.report_usage("on_edit_join_grb()")
  2911. objs = self.collection.get_selected()
  2912. for obj in objs:
  2913. if not isinstance(obj, FlatCAMGerber):
  2914. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2915. return
  2916. def initialize(obj, app):
  2917. FlatCAMGerber.merge(objs, obj)
  2918. self.new_object("gerber", 'Combo_Gerber', initialize)
  2919. self.should_we_save = True
  2920. def on_convert_singlegeo_to_multigeo(self):
  2921. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2922. obj = self.collection.get_active()
  2923. if obj is None:
  2924. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2925. return
  2926. if not isinstance(obj, FlatCAMGeometry):
  2927. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2928. return
  2929. obj.multigeo = True
  2930. for tooluid, dict_value in obj.tools.items():
  2931. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2932. if not isinstance(obj.solid_geometry, list):
  2933. obj.solid_geometry = [obj.solid_geometry]
  2934. obj.solid_geometry[:] = []
  2935. obj.plot()
  2936. self.should_we_save = True
  2937. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2938. def on_convert_multigeo_to_singlegeo(self):
  2939. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2940. obj = self.collection.get_active()
  2941. if obj is None:
  2942. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2943. return
  2944. if not isinstance(obj, FlatCAMGeometry):
  2945. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2946. return
  2947. obj.multigeo = False
  2948. total_solid_geometry = []
  2949. for tooluid, dict_value in obj.tools.items():
  2950. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2951. # clear the original geometry
  2952. dict_value['solid_geometry'][:] = []
  2953. obj.solid_geometry = deepcopy(total_solid_geometry)
  2954. obj.plot()
  2955. self.should_we_save = True
  2956. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2957. def on_options_dict_change(self, field):
  2958. self.options_write_form_field(field)
  2959. if field == "units":
  2960. self.set_screen_units(self.options['units'])
  2961. def on_defaults_dict_change(self, field):
  2962. self.defaults_write_form_field(field)
  2963. if field == "units":
  2964. self.set_screen_units(self.defaults['units'])
  2965. def set_screen_units(self, units):
  2966. self.ui.units_label.setText("[" + units.lower() + "]")
  2967. def on_toggle_units(self, no_pref=False):
  2968. """
  2969. Callback for the Units radio-button change in the Options tab.
  2970. Changes the application's default units or the current project's units.
  2971. If changing the project's units, the change propagates to all of
  2972. the objects in the project.
  2973. :return: None
  2974. """
  2975. self.report_usage("on_toggle_units")
  2976. if self.toggle_units_ignore:
  2977. return
  2978. # If option is the same, then ignore
  2979. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2980. self.defaults["units"].upper():
  2981. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2982. return
  2983. # Options to scale
  2984. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2985. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2986. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2987. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2988. "excellon_z_pdepth",
  2989. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2990. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2991. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2992. "geometry_feedrate_probe",
  2993. 'cncjob_tooldia',
  2994. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2995. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2996. "tools_2sided_drilldia", "tools_film_boundary",
  2997. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2998. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2999. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3000. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3001. "tools_transform_offset_y",
  3002. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3003. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3004. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3005. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3006. 'global_gridx', 'global_gridy', 'global_snap_max']
  3007. def scale_options(sfactor):
  3008. for dim in dimensions:
  3009. if dim == 'excellon_toolchangexy':
  3010. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3011. coords_xy[0] *= sfactor
  3012. coords_xy[1] *= sfactor
  3013. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3014. elif dim == 'geometry_toolchangexy':
  3015. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3016. coords_xy[0] *= sfactor
  3017. coords_xy[1] *= sfactor
  3018. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3019. elif dim == 'tools_ncctools':
  3020. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3021. ncctols[0] *= sfactor
  3022. ncctols[1] *= sfactor
  3023. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  3024. elif dim == 'tools_solderpaste_tools':
  3025. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3026. sp_tools[0] *= sfactor
  3027. sp_tools[1] *= sfactor
  3028. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  3029. elif dim == 'tools_solderpaste_xy_toolchange':
  3030. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3031. sp_coords[0] *= sfactor
  3032. sp_coords[1] *= sfactor
  3033. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3034. else:
  3035. try:
  3036. self.options[dim] = float(self.options[dim]) * sfactor
  3037. except Exception as e:
  3038. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3039. def scale_defaults(sfactor):
  3040. for dim in dimensions:
  3041. if dim == 'excellon_toolchangexy':
  3042. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3043. coords_xy[0] *= sfactor
  3044. coords_xy[1] *= sfactor
  3045. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3046. elif dim == 'geometry_toolchangexy':
  3047. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3048. coords_xy[0] *= sfactor
  3049. coords_xy[1] *= sfactor
  3050. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3051. elif dim == 'tools_ncctools':
  3052. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3053. ncctols[0] *= sfactor
  3054. ncctols[1] *= sfactor
  3055. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  3056. elif dim == 'tools_solderpaste_tools':
  3057. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3058. sp_tools[0] *= sfactor
  3059. sp_tools[1] *= sfactor
  3060. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  3061. elif dim == 'tools_solderpaste_xy_toolchange':
  3062. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3063. sp_coords[0] *= sfactor
  3064. sp_coords[1] *= sfactor
  3065. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3066. else:
  3067. try:
  3068. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  3069. except Exception as e:
  3070. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3071. # The scaling factor depending on choice of units.
  3072. factor = 1/25.4
  3073. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3074. factor = 25.4
  3075. # Changing project units. Warn user.
  3076. msgbox = QtWidgets.QMessageBox()
  3077. msgbox.setWindowTitle("Toggle Units")
  3078. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3079. msgbox.setText("<B>Change project units ...</B>")
  3080. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  3081. "properties of all objects to be scaled accordingly.\nContinue?")
  3082. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3083. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3084. msgbox.setDefaultButton(bt_ok)
  3085. msgbox.exec_()
  3086. response = msgbox.clickedButton()
  3087. if response == bt_ok:
  3088. if no_pref is False:
  3089. self.options_read_form()
  3090. scale_options(factor)
  3091. self.options_write_form()
  3092. self.defaults_read_form()
  3093. scale_defaults(factor)
  3094. self.defaults_write_form()
  3095. self.should_we_save = True
  3096. # change this only if the workspace is active
  3097. if self.defaults['global_workspace'] is True:
  3098. self.plotcanvas.draw_workspace()
  3099. # adjust the grid values on the main toolbar
  3100. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  3101. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  3102. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3103. for obj in self.collection.get_list():
  3104. obj.convert_units(units)
  3105. # make that the properties stored in the object are also updated
  3106. self.object_changed.emit(obj)
  3107. obj.build_ui()
  3108. current = self.collection.get_active()
  3109. if current is not None:
  3110. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3111. if not isinstance(current, FlatCAMGeometry):
  3112. current.to_form()
  3113. self.plot_all()
  3114. self.inform.emit(_("[success] Converted units to %s") % units)
  3115. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3116. self.set_screen_units(units)
  3117. else:
  3118. # Undo toggling
  3119. self.toggle_units_ignore = True
  3120. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3121. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3122. else:
  3123. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3124. self.toggle_units_ignore = False
  3125. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3126. self.options_read_form()
  3127. self.defaults_read_form()
  3128. def on_toggle_units_click(self):
  3129. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3130. if self.defaults["units"] == 'MM':
  3131. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3132. else:
  3133. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3134. self.on_toggle_units(no_pref=True)
  3135. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3136. lambda: self.on_toggle_units(no_pref=False))
  3137. def on_fullscreen(self):
  3138. self.report_usage("on_fullscreen()")
  3139. if self.toggle_fscreen is False:
  3140. if sys.platform == 'win32':
  3141. self.ui.showFullScreen()
  3142. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3143. tb.setVisible(False)
  3144. self.ui.splitter_left.setVisible(False)
  3145. self.toggle_fscreen = True
  3146. else:
  3147. if sys.platform == 'win32':
  3148. self.ui.showNormal()
  3149. self.restore_toolbar_view()
  3150. self.ui.splitter_left.setVisible(True)
  3151. self.toggle_fscreen = False
  3152. def on_toggle_plotarea(self):
  3153. self.report_usage("on_toggle_plotarea()")
  3154. try:
  3155. name = self.ui.plot_tab_area.widget(0).objectName()
  3156. except AttributeError:
  3157. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3158. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3159. self.ui.plot_tab_area.protectTab(0)
  3160. return
  3161. if name != 'plotarea':
  3162. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3163. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3164. self.ui.plot_tab_area.protectTab(0)
  3165. else:
  3166. self.ui.plot_tab_area.closeTab(0)
  3167. def on_toggle_notebook(self):
  3168. if self.ui.splitter.sizes()[0] == 0:
  3169. self.ui.splitter.setSizes([1, 1])
  3170. else:
  3171. self.ui.splitter.setSizes([0, 1])
  3172. def on_toggle_axis(self):
  3173. self.report_usage("on_toggle_axis()")
  3174. if self.toggle_axis is False:
  3175. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3176. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3177. self.plotcanvas.redraw()
  3178. self.toggle_axis = True
  3179. else:
  3180. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3181. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3182. self.plotcanvas.redraw()
  3183. self.toggle_axis = False
  3184. def on_toggle_grid(self):
  3185. self.report_usage("on_toggle_grid()")
  3186. self.ui.grid_snap_btn.trigger()
  3187. def on_options_combo_change(self, sel):
  3188. """
  3189. Called when the combo box to choose between application defaults and
  3190. project option changes value. The corresponding variables are
  3191. copied to the UI.
  3192. :param sel: The option index that was chosen.
  3193. :return: None
  3194. """
  3195. # combo_sel = self.ui.notebook.combo_options.get_active()
  3196. App.log.debug("Options --> %s" % sel)
  3197. # form = [self.defaults_form, self.options_form][sel]
  3198. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3199. if sel == 0:
  3200. self.gen_form = self.ui.general_defaults_form
  3201. self.ger_form = self.ui.gerber_defaults_form
  3202. self.exc_form = self.ui.excellon_defaults_form
  3203. self.geo_form = self.ui.geometry_defaults_form
  3204. self.cnc_form = self.ui.cncjob_defaults_form
  3205. self.tools_form = self.ui.tools_defaults_form
  3206. elif sel == 1:
  3207. self.gen_form = self.ui.general_options_form
  3208. self.ger_form = self.ui.gerber_options_form
  3209. self.exc_form = self.ui.excellon_options_form
  3210. self.geo_form = self.ui.geometry_options_form
  3211. self.cnc_form = self.ui.cncjob_options_form
  3212. self.tools_form = self.ui.tools_options_form
  3213. else:
  3214. return
  3215. try:
  3216. self.ui.general_scroll_area.takeWidget()
  3217. except:
  3218. self.log.debug("Nothing to remove")
  3219. self.ui.general_scroll_area.setWidget(self.gen_form)
  3220. self.gen_form.show()
  3221. try:
  3222. self.ui.gerber_scroll_area.takeWidget()
  3223. except:
  3224. self.log.debug("Nothing to remove")
  3225. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3226. self.ger_form.show()
  3227. try:
  3228. self.ui.excellon_scroll_area.takeWidget()
  3229. except:
  3230. self.log.debug("Nothing to remove")
  3231. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3232. self.exc_form.show()
  3233. try:
  3234. self.ui.geometry_scroll_area.takeWidget()
  3235. except:
  3236. self.log.debug("Nothing to remove")
  3237. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3238. self.geo_form.show()
  3239. try:
  3240. self.ui.cncjob_scroll_area.takeWidget()
  3241. except:
  3242. self.log.debug("Nothing to remove")
  3243. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3244. self.cnc_form.show()
  3245. try:
  3246. self.ui.tools_scroll_area.takeWidget()
  3247. except:
  3248. self.log.debug("Nothing to remove")
  3249. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3250. self.tools_form.show()
  3251. self.log.debug("Finished GUI form initialization.")
  3252. # self.options2form()
  3253. def on_excellon_defaults_button(self):
  3254. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3255. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3256. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3257. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3258. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3259. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3260. log.debug("Excellon app defaults loaded ...")
  3261. def on_excellon_options_button(self):
  3262. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3263. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3264. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3265. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3266. self.options_form_fields["excellon_zeros"].set_value('L')
  3267. self.options_form_fields["excellon_units"].set_value('INCH')
  3268. log.debug("Excellon options defaults loaded ...")
  3269. # Setting plot colors handlers
  3270. def on_pf_color_entry(self):
  3271. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3272. self.defaults['global_plot_fill'][7:9]
  3273. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3274. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3275. def on_pf_color_button(self):
  3276. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3277. c_dialog = QtWidgets.QColorDialog()
  3278. plot_fill_color = c_dialog.getColor(initial=current_color)
  3279. if plot_fill_color.isValid() is False:
  3280. return
  3281. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3282. "background-color:%s" % str(plot_fill_color.name()))
  3283. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3284. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3285. self.defaults['global_plot_fill'] = new_val
  3286. def on_pf_color_spinner(self):
  3287. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3288. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3289. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3290. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3291. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3292. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3293. def on_pf_color_slider(self):
  3294. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3295. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3296. def on_pl_color_entry(self):
  3297. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3298. self.defaults['global_plot_line'][7:9]
  3299. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3300. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3301. def on_pl_color_button(self):
  3302. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3303. # print(current_color)
  3304. c_dialog = QtWidgets.QColorDialog()
  3305. plot_line_color = c_dialog.getColor(initial=current_color)
  3306. if plot_line_color.isValid() is False:
  3307. return
  3308. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3309. "background-color:%s" % str(plot_line_color.name()))
  3310. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3311. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3312. self.defaults['global_plot_line'] = new_val_line
  3313. # Setting selection colors (left - right) handlers
  3314. def on_sf_color_entry(self):
  3315. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3316. self.defaults['global_sel_fill'][7:9]
  3317. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3318. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3319. def on_sf_color_button(self):
  3320. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3321. c_dialog = QtWidgets.QColorDialog()
  3322. plot_fill_color = c_dialog.getColor(initial=current_color)
  3323. if plot_fill_color.isValid() is False:
  3324. return
  3325. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3326. "background-color:%s" % str(plot_fill_color.name()))
  3327. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3328. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3329. self.defaults['global_sel_fill'] = new_val
  3330. def on_sf_color_spinner(self):
  3331. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3332. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3333. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3334. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3335. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3336. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3337. def on_sf_color_slider(self):
  3338. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3339. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3340. def on_sl_color_entry(self):
  3341. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3342. self.defaults['global_sel_line'][7:9]
  3343. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3344. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3345. def on_sl_color_button(self):
  3346. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3347. c_dialog = QtWidgets.QColorDialog()
  3348. plot_line_color = c_dialog.getColor(initial=current_color)
  3349. if plot_line_color.isValid() is False:
  3350. return
  3351. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3352. "background-color:%s" % str(plot_line_color.name()))
  3353. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3354. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3355. self.defaults['global_sel_line'] = new_val_line
  3356. # Setting selection colors (right - left) handlers
  3357. def on_alt_sf_color_entry(self):
  3358. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3359. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3360. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3361. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3362. def on_alt_sf_color_button(self):
  3363. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3364. c_dialog = QtWidgets.QColorDialog()
  3365. plot_fill_color = c_dialog.getColor(initial=current_color)
  3366. if plot_fill_color.isValid() is False:
  3367. return
  3368. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3369. "background-color:%s" % str(plot_fill_color.name()))
  3370. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3371. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3372. self.defaults['global_alt_sel_fill'] = new_val
  3373. def on_alt_sf_color_spinner(self):
  3374. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3375. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3376. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3377. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3378. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3379. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3380. def on_alt_sf_color_slider(self):
  3381. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3382. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3383. def on_alt_sl_color_entry(self):
  3384. self.defaults['global_alt_sel_line'] = \
  3385. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3386. self.defaults['global_alt_sel_line'][7:9]
  3387. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3388. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3389. def on_alt_sl_color_button(self):
  3390. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3391. c_dialog = QtWidgets.QColorDialog()
  3392. plot_line_color = c_dialog.getColor(initial=current_color)
  3393. if plot_line_color.isValid() is False:
  3394. return
  3395. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3396. "background-color:%s" % str(plot_line_color.name()))
  3397. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3398. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3399. self.defaults['global_alt_sel_line'] = new_val_line
  3400. # Setting Editor colors
  3401. def on_draw_color_entry(self):
  3402. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3403. .draw_color_entry.get_value()
  3404. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3405. "background-color:%s" % str(self.defaults['global_draw_color']))
  3406. def on_draw_color_button(self):
  3407. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3408. c_dialog = QtWidgets.QColorDialog()
  3409. draw_color = c_dialog.getColor(initial=current_color)
  3410. if draw_color.isValid() is False:
  3411. return
  3412. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3413. "background-color:%s" % str(draw_color.name()))
  3414. new_val = str(draw_color.name())
  3415. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3416. self.defaults['global_draw_color'] = new_val
  3417. def on_sel_draw_color_entry(self):
  3418. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3419. .sel_draw_color_entry.get_value()
  3420. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3421. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3422. def on_sel_draw_color_button(self):
  3423. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3424. c_dialog = QtWidgets.QColorDialog()
  3425. sel_draw_color = c_dialog.getColor(initial=current_color)
  3426. if sel_draw_color.isValid() is False:
  3427. return
  3428. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3429. "background-color:%s" % str(sel_draw_color.name()))
  3430. new_val_sel = str(sel_draw_color.name())
  3431. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3432. self.defaults['global_sel_draw_color'] = new_val_sel
  3433. def on_proj_color_entry(self):
  3434. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3435. .proj_color_entry.get_value()
  3436. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3437. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3438. def on_proj_color_button(self):
  3439. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3440. c_dialog = QtWidgets.QColorDialog()
  3441. proj_color = c_dialog.getColor(initial=current_color)
  3442. if proj_color.isValid() is False:
  3443. return
  3444. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3445. "background-color:%s" % str(proj_color.name()))
  3446. new_val_sel = str(proj_color.name())
  3447. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3448. self.defaults['global_proj_item_color'] = new_val_sel
  3449. def on_proj_color_dis_entry(self):
  3450. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3451. .proj_color_dis_entry.get_value()
  3452. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3453. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3454. def on_proj_color_dis_button(self):
  3455. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3456. c_dialog = QtWidgets.QColorDialog()
  3457. proj_color = c_dialog.getColor(initial=current_color)
  3458. if proj_color.isValid() is False:
  3459. return
  3460. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3461. "background-color:%s" % str(proj_color.name()))
  3462. new_val_sel = str(proj_color.name())
  3463. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3464. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3465. def on_deselect_all(self):
  3466. self.collection.set_all_inactive()
  3467. self.delete_selection_shape()
  3468. def on_workspace_modified(self):
  3469. self.save_defaults(silent=True)
  3470. self.plotcanvas.draw_workspace()
  3471. def on_workspace(self):
  3472. self.report_usage("on_workspace()")
  3473. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3474. self.plotcanvas.restore_workspace()
  3475. else:
  3476. self.plotcanvas.delete_workspace()
  3477. self.save_defaults(silent=True)
  3478. def on_workspace_menu(self):
  3479. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3480. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3481. else:
  3482. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3483. self.on_workspace()
  3484. def on_layout(self, index=None, lay=None):
  3485. self.report_usage("on_layout()")
  3486. if lay:
  3487. current_layout = lay
  3488. else:
  3489. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3490. settings = QSettings("Open Source", "FlatCAM")
  3491. settings.setValue('layout', current_layout)
  3492. # This will write the setting to the platform specific storage.
  3493. del settings
  3494. # first remove the toolbars:
  3495. try:
  3496. self.ui.removeToolBar(self.ui.toolbarfile)
  3497. self.ui.removeToolBar(self.ui.toolbargeo)
  3498. self.ui.removeToolBar(self.ui.toolbarview)
  3499. self.ui.removeToolBar(self.ui.toolbarshell)
  3500. self.ui.removeToolBar(self.ui.toolbartools)
  3501. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3502. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3503. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3504. self.ui.removeToolBar(self.ui.snap_toolbar)
  3505. self.ui.removeToolBar(self.ui.toolbarshell)
  3506. except:
  3507. pass
  3508. if current_layout == 'standard':
  3509. # ## TOOLBAR INSTALLATION # ##
  3510. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3511. self.ui.toolbarfile.setObjectName('File_TB')
  3512. self.ui.addToolBar(self.ui.toolbarfile)
  3513. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3514. self.ui.toolbargeo.setObjectName('Edit_TB')
  3515. self.ui.addToolBar(self.ui.toolbargeo)
  3516. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3517. self.ui.toolbarview.setObjectName('View_TB')
  3518. self.ui.addToolBar(self.ui.toolbarview)
  3519. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3520. self.ui.toolbarshell.setObjectName('Shell_TB')
  3521. self.ui.addToolBar(self.ui.toolbarshell)
  3522. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3523. self.ui.toolbartools.setObjectName('Tools_TB')
  3524. self.ui.addToolBar(self.ui.toolbartools)
  3525. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3526. self.ui.exc_edit_toolbar.setVisible(False)
  3527. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3528. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3529. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3530. self.ui.geo_edit_toolbar.setVisible(False)
  3531. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3532. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3533. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3534. self.ui.grb_edit_toolbar.setVisible(False)
  3535. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3536. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3537. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3538. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3539. # self.ui.snap_toolbar.setMaximumHeight(30)
  3540. self.ui.addToolBar(self.ui.snap_toolbar)
  3541. self.ui.corner_snap_btn.setVisible(False)
  3542. self.ui.snap_magnet.setVisible(False)
  3543. elif current_layout == 'compact':
  3544. # ## TOOLBAR INSTALLATION # ##
  3545. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3546. self.ui.toolbarfile.setObjectName('File_TB')
  3547. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3548. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3549. self.ui.toolbargeo.setObjectName('Edit_TB')
  3550. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3551. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3552. self.ui.toolbarview.setObjectName('View_TB')
  3553. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3554. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3555. self.ui.toolbarshell.setObjectName('Shell_TB')
  3556. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3557. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3558. self.ui.toolbartools.setObjectName('Tools_TB')
  3559. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3560. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3561. # self.ui.geo_edit_toolbar.setVisible(False)
  3562. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3563. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3564. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3565. # self.ui.grb_edit_toolbar.setVisible(False)
  3566. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3567. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3568. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3569. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3570. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3571. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3572. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3573. self.ui.snap_toolbar.setMaximumHeight(30)
  3574. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3575. self.ui.corner_snap_btn.setVisible(True)
  3576. self.ui.snap_magnet.setVisible(True)
  3577. # add all the actions to the toolbars
  3578. self.ui.populate_toolbars()
  3579. # reconnect all the signals to the toolbar actions
  3580. self.connect_toolbar_signals()
  3581. self.ui.grid_snap_btn.setChecked(True)
  3582. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3583. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3584. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3585. self.ui.grid_gap_link_cb.setChecked(True)
  3586. def on_cnc_custom_parameters(self, signal_text):
  3587. if signal_text == 'Parameters':
  3588. return
  3589. else:
  3590. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3591. def on_save_button(self):
  3592. self.save_defaults(silent=False)
  3593. # load the defaults so they are updated into the app
  3594. self.load_defaults(filename='current_defaults')
  3595. # Re-fresh project options
  3596. self.on_options_app2project()
  3597. def handlePrint(self):
  3598. self.report_usage("handlePrint()")
  3599. dialog = QtPrintSupport.QPrintDialog()
  3600. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3601. self.ui.code_editor.document().print_(dialog.printer())
  3602. def handlePreview(self):
  3603. self.report_usage("handlePreview()")
  3604. dialog = QtPrintSupport.QPrintPreviewDialog()
  3605. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3606. dialog.exec_()
  3607. def handleTextChanged(self):
  3608. # enable = not self.ui.code_editor.document().isEmpty()
  3609. # self.ui.buttonPrint.setEnabled(enable)
  3610. # self.ui.buttonPreview.setEnabled(enable)
  3611. pass
  3612. def handleOpen(self, filt=None):
  3613. self.report_usage("handleOpen()")
  3614. if filt:
  3615. _filter_ = filt
  3616. else:
  3617. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3618. "All Files (*.*)"
  3619. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3620. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3621. if path:
  3622. file = QtCore.QFile(path)
  3623. if file.open(QtCore.QIODevice.ReadOnly):
  3624. stream = QtCore.QTextStream(file)
  3625. self.gcode_edited = stream.readAll()
  3626. self.ui.code_editor.setPlainText(self.gcode_edited)
  3627. file.close()
  3628. def handleSaveGCode(self, name=None, filt=None):
  3629. self.report_usage("handleSaveGCode()")
  3630. if filt:
  3631. _filter_ = filt
  3632. else:
  3633. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3634. "All Files (*.*)"
  3635. if name:
  3636. obj_name = name
  3637. else:
  3638. try:
  3639. obj_name = self.collection.get_active().options['name']
  3640. except AttributeError:
  3641. obj_name = 'file'
  3642. if filt is None:
  3643. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3644. try:
  3645. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3646. caption=_("Export G-Code ..."),
  3647. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3648. filter=_filter_
  3649. )[0])
  3650. except TypeError:
  3651. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3652. if filename == "":
  3653. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3654. return
  3655. else:
  3656. try:
  3657. my_gcode = self.ui.code_editor.toPlainText()
  3658. with open(filename, 'w') as f:
  3659. for line in my_gcode:
  3660. f.write(line)
  3661. except FileNotFoundError:
  3662. self.inform.emit(_("[WARNING] No such file or directory"))
  3663. return
  3664. # Just for adding it to the recent files list.
  3665. if self.defaults["global_open_style"] is False:
  3666. self.file_opened.emit("cncjob", filename)
  3667. self.file_saved.emit("cncjob", filename)
  3668. self.inform.emit(_("Saved to: %s") % filename)
  3669. def handleFindGCode(self):
  3670. self.report_usage("handleFindGCode()")
  3671. flags = QtGui.QTextDocument.FindCaseSensitively
  3672. text_to_be_found = self.ui.entryFind.get_value()
  3673. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3674. if r is False:
  3675. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3676. def handleReplaceGCode(self):
  3677. self.report_usage("handleReplaceGCode()")
  3678. old = self.ui.entryFind.get_value()
  3679. new = self.ui.entryReplace.get_value()
  3680. if self.ui.sel_all_cb.isChecked():
  3681. while True:
  3682. cursor = self.ui.code_editor.textCursor()
  3683. cursor.beginEditBlock()
  3684. flags = QtGui.QTextDocument.FindCaseSensitively
  3685. # self.ui.editor is the QPlainTextEdit
  3686. r = self.ui.code_editor.find(str(old), flags)
  3687. if r:
  3688. qc = self.ui.code_editor.textCursor()
  3689. if qc.hasSelection():
  3690. qc.insertText(new)
  3691. else:
  3692. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3693. break
  3694. # Mark end of undo block
  3695. cursor.endEditBlock()
  3696. else:
  3697. cursor = self.ui.code_editor.textCursor()
  3698. cursor.beginEditBlock()
  3699. qc = self.ui.code_editor.textCursor()
  3700. if qc.hasSelection():
  3701. qc.insertText(new)
  3702. # Mark end of undo block
  3703. cursor.endEditBlock()
  3704. def on_tool_add_keypress(self):
  3705. # ## Current application units in Upper Case
  3706. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3707. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3708. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3709. if notebook_widget_name == 'selected_tab':
  3710. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3711. # Tool add works for Geometry only if Advanced is True in Preferences
  3712. if self.defaults["global_app_level"] == 'a':
  3713. tool_add_popup = FCInputDialog(title="New Tool ...",
  3714. text='Enter a Tool Diameter:',
  3715. min=0.0000, max=99.9999, decimals=4)
  3716. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3717. val, ok = tool_add_popup.get_value()
  3718. if ok:
  3719. if float(val) == 0:
  3720. self.inform.emit(
  3721. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3722. return
  3723. self.collection.get_active().on_tool_add(dia=float(val))
  3724. else:
  3725. self.inform.emit(
  3726. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3727. else:
  3728. msgbox = QtWidgets.QMessageBox()
  3729. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3730. "Go to Preferences -> General - Show Advanced Options."))
  3731. msgbox.setWindowTitle("Tool adding ...")
  3732. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3733. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3734. msgbox.setDefaultButton(bt_ok)
  3735. msgbox.exec_()
  3736. # work only if the notebook tab on focus is the Tools_Tab
  3737. if notebook_widget_name == 'tool_tab':
  3738. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3739. tool_add_popup = FCInputDialog(title="New Tool ...",
  3740. text='Enter a Tool Diameter:',
  3741. min=0.0000, max=99.9999, decimals=4)
  3742. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3743. val, ok = tool_add_popup.get_value()
  3744. # and only if the tool is NCC Tool
  3745. if tool_widget == self.ncclear_tool.toolName:
  3746. if ok:
  3747. if float(val) == 0:
  3748. self.inform.emit(
  3749. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3750. return
  3751. self.ncclear_tool.on_tool_add(dia=float(val))
  3752. else:
  3753. self.inform.emit(
  3754. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3755. # and only if the tool is Paint Area Tool
  3756. elif tool_widget == self.paint_tool.toolName:
  3757. if ok:
  3758. if float(val) == 0:
  3759. self.inform.emit(
  3760. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3761. return
  3762. self.paint_tool.on_tool_add(dia=float(val))
  3763. else:
  3764. self.inform.emit(
  3765. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3766. # and only if the tool is Solder Paste Dispensing Tool
  3767. elif tool_widget == self.paste_tool.toolName:
  3768. if ok:
  3769. if float(val) == 0:
  3770. self.inform.emit(
  3771. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3772. return
  3773. self.paste_tool.on_tool_add(dia=float(val))
  3774. else:
  3775. self.inform.emit(
  3776. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3777. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3778. # See description bellow.
  3779. def on_delete_keypress(self):
  3780. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3781. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3782. if notebook_widget_name == 'selected_tab':
  3783. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3784. self.collection.get_active().on_tool_delete()
  3785. # work only if the notebook tab on focus is the Tools_Tab
  3786. elif notebook_widget_name == 'tool_tab':
  3787. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3788. # and only if the tool is NCC Tool
  3789. if tool_widget == self.ncclear_tool.toolName:
  3790. self.ncclear_tool.on_tool_delete()
  3791. # and only if the tool is Paint Tool
  3792. elif tool_widget == self.paint_tool.toolName:
  3793. self.paint_tool.on_tool_delete()
  3794. # and only if the tool is Solder Paste Dispensing Tool
  3795. elif tool_widget == self.paste_tool.toolName:
  3796. self.paste_tool.on_tool_delete()
  3797. else:
  3798. self.on_delete()
  3799. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3800. # some screens you have to be careful where you hover with your mouse.
  3801. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3802. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3803. # Complicated, I know :)
  3804. def on_delete(self):
  3805. """
  3806. Delete the currently selected FlatCAMObjs.
  3807. :return: None
  3808. """
  3809. self.report_usage("on_delete()")
  3810. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3811. # a geometry object before we update it.
  3812. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3813. if self.collection.get_active():
  3814. self.log.debug("on_delete()")
  3815. self.report_usage("on_delete")
  3816. while (self.collection.get_active()):
  3817. obj_active = self.collection.get_active()
  3818. # if the deleted object is FlatCAMGerber then make sure to delete the possbile mark shapes
  3819. if isinstance(obj_active, FlatCAMGerber):
  3820. for el in obj_active.mark_shapes:
  3821. obj_active.mark_shapes[el].clear(update=True)
  3822. obj_active.mark_shapes[el].enabled = False
  3823. obj_active.mark_shapes[el] = None
  3824. self.delete_first_selected()
  3825. self.inform.emit(_("Object(s) deleted ..."))
  3826. # make sure that the selection shape is deleted, too
  3827. self.delete_selection_shape()
  3828. else:
  3829. self.inform.emit(_("Failed. No object(s) selected..."))
  3830. else:
  3831. self.inform.emit(_("Save the work in Editor and try again ..."))
  3832. def on_set_origin(self):
  3833. """
  3834. Set the origin to the left mouse click position
  3835. :return: None
  3836. """
  3837. # display the message for the user
  3838. # and ask him to click on the desired position
  3839. self.report_usage("on_set_origin()")
  3840. self.inform.emit(_('Click to set the origin ...'))
  3841. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3842. def on_jump_to(self, custom_location=None, fit_center=True):
  3843. """
  3844. Jump to a location by setting the mouse cursor location
  3845. :return:
  3846. """
  3847. self.report_usage("on_jump_to()")
  3848. if not custom_location:
  3849. dia_box = Dialog_box(title=_("Jump to ..."),
  3850. label=_("Enter the coordinates in format X,Y:"),
  3851. icon=QtGui.QIcon('share/jump_to16.png'))
  3852. if dia_box.ok is True:
  3853. try:
  3854. location = eval(dia_box.location)
  3855. if not isinstance(location, tuple):
  3856. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3857. return
  3858. except:
  3859. return
  3860. else:
  3861. return
  3862. else:
  3863. location = custom_location
  3864. if fit_center:
  3865. self.plotcanvas.fit_center(loc=location)
  3866. cursor = QtGui.QCursor()
  3867. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3868. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3869. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3870. self.inform.emit(_("[success] Done."))
  3871. def on_copy_object(self):
  3872. self.report_usage("on_copy_object()")
  3873. def initialize(obj_init, app):
  3874. obj_init.solid_geometry = obj.solid_geometry
  3875. try:
  3876. obj_init.follow_geometry = obj.follow_geometry
  3877. except AttributeError:
  3878. pass
  3879. try:
  3880. obj_init.apertures = obj.apertures
  3881. except AttributeError:
  3882. pass
  3883. try:
  3884. if obj.tools:
  3885. obj_init.tools = obj.tools
  3886. except Exception as e:
  3887. log.debug("App.on_copy_object() --> %s" % str(e))
  3888. def initialize_excellon(obj_init, app):
  3889. obj_init.tools = obj.tools
  3890. # drills are offset, so they need to be deep copied
  3891. obj_init.drills = deepcopy(obj.drills)
  3892. # slots are offset, so they need to be deep copied
  3893. obj_init.slots = deepcopy(obj.slots)
  3894. obj_init.create_geometry()
  3895. for obj in self.collection.get_selected():
  3896. obj_name = obj.options["name"]
  3897. try:
  3898. if isinstance(obj, FlatCAMExcellon):
  3899. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3900. elif isinstance(obj,FlatCAMGerber):
  3901. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3902. elif isinstance(obj,FlatCAMGeometry):
  3903. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3904. except Exception as e:
  3905. return "Operation failed: %s" % str(e)
  3906. def on_copy_object2(self, custom_name):
  3907. def initialize_geometry(obj_init, app):
  3908. obj_init.solid_geometry = obj.solid_geometry
  3909. try:
  3910. obj_init.follow_geometry = obj.follow_geometry
  3911. except AttributeError:
  3912. pass
  3913. try:
  3914. obj_init.apertures = obj.apertures
  3915. except AttributeError:
  3916. pass
  3917. try:
  3918. if obj.tools:
  3919. obj_init.tools = obj.tools
  3920. except Exception as e:
  3921. log.debug("on_copy_object2() --> %s" % str(e))
  3922. def initialize_gerber(obj_init, app):
  3923. obj_init.solid_geometry = obj.solid_geometry
  3924. obj_init.apertures = deepcopy(obj.apertures)
  3925. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3926. def initialize_excellon(obj_init, app):
  3927. obj_init.tools = obj.tools
  3928. # drills are offset, so they need to be deep copied
  3929. obj_init.drills = deepcopy(obj.drills)
  3930. # slots are offset, so they need to be deep copied
  3931. obj_init.slots = deepcopy(obj.slots)
  3932. obj_init.create_geometry()
  3933. for obj in self.collection.get_selected():
  3934. obj_name = obj.options["name"]
  3935. try:
  3936. if isinstance(obj, FlatCAMExcellon):
  3937. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3938. elif isinstance(obj,FlatCAMGerber):
  3939. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3940. elif isinstance(obj,FlatCAMGeometry):
  3941. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3942. except Exception as e:
  3943. return "Operation failed: %s" % str(e)
  3944. def on_rename_object(self, text):
  3945. self.report_usage("on_rename_object()")
  3946. named_obj = self.collection.get_active()
  3947. for obj in named_obj:
  3948. if obj is list:
  3949. self.on_rename_object(text)
  3950. else:
  3951. try:
  3952. obj.options['name'] = text
  3953. except Exception as e:
  3954. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  3955. def convert_any2geo(self):
  3956. self.report_usage("convert_any2geo()")
  3957. def initialize(obj_init, app):
  3958. obj_init.solid_geometry = obj.solid_geometry
  3959. try:
  3960. obj_init.follow_geometry = obj.follow_geometry
  3961. except AttributeError:
  3962. pass
  3963. try:
  3964. obj_init.apertures = obj.apertures
  3965. except AttributeError:
  3966. pass
  3967. try:
  3968. if obj.tools:
  3969. obj_init.tools = obj.tools
  3970. except AttributeError:
  3971. pass
  3972. def initialize_excellon(obj_init, app):
  3973. # objs = self.collection.get_selected()
  3974. # FlatCAMGeometry.merge(objs, obj)
  3975. solid_geo = []
  3976. for tool in obj.tools:
  3977. for geo in obj.tools[tool]['solid_geometry']:
  3978. solid_geo.append(geo)
  3979. obj_init.solid_geometry = deepcopy(solid_geo)
  3980. if not self.collection.get_selected():
  3981. log.warning("App.convert_any2geo --> No object selected")
  3982. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  3983. return
  3984. for obj in self.collection.get_selected():
  3985. obj_name = obj.options["name"]
  3986. try:
  3987. if isinstance(obj, FlatCAMExcellon):
  3988. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  3989. else:
  3990. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  3991. except Exception as e:
  3992. return "Operation failed: %s" % str(e)
  3993. def convert_any2gerber(self):
  3994. self.report_usage("convert_any2gerber()")
  3995. def initialize_geometry(obj_init, app):
  3996. apertures = {}
  3997. apid = 0
  3998. apertures[str(apid)] = {}
  3999. apertures[str(apid)]['geometry'] = []
  4000. for obj_orig in obj.solid_geometry:
  4001. new_elem = dict()
  4002. new_elem['solid'] = obj_orig
  4003. new_elem['follow'] = obj_orig.exterior
  4004. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4005. apertures[str(apid)]['size'] = 0.0
  4006. apertures[str(apid)]['type'] = 'C'
  4007. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4008. obj_init.apertures = deepcopy(apertures)
  4009. def initialize_excellon(obj_init, app):
  4010. apertures = {}
  4011. apid = 10
  4012. for tool in obj.tools:
  4013. apertures[str(apid)] = {}
  4014. apertures[str(apid)]['geometry'] = []
  4015. for geo in obj.tools[tool]['solid_geometry']:
  4016. new_el = dict()
  4017. new_el['solid'] = geo
  4018. new_el['follow'] = geo.exterior
  4019. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4020. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4021. apertures[str(apid)]['type'] = 'C'
  4022. apid += 1
  4023. # create solid_geometry
  4024. solid_geometry = []
  4025. for apid in apertures:
  4026. for geo_el in apertures[apid]['geometry']:
  4027. solid_geometry.append(geo_el['solid'])
  4028. solid_geometry = MultiPolygon(solid_geometry)
  4029. solid_geometry = solid_geometry.buffer(0.0000001)
  4030. obj_init.solid_geometry = deepcopy(solid_geometry)
  4031. obj_init.apertures = deepcopy(apertures)
  4032. # clear the working objects (perhaps not necessary due of Python GC)
  4033. apertures.clear()
  4034. if not self.collection.get_selected():
  4035. log.warning("App.convert_any2gerber --> No object selected")
  4036. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4037. return
  4038. for obj in self.collection.get_selected():
  4039. obj_name = obj.options["name"]
  4040. try:
  4041. if isinstance(obj, FlatCAMExcellon):
  4042. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4043. elif isinstance(obj, FlatCAMGeometry):
  4044. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4045. else:
  4046. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4047. except Exception as e:
  4048. return "Operation failed: %s" % str(e)
  4049. def on_set_zero_click(self, event):
  4050. #this function will be available only for mouse left click
  4051. pos =[]
  4052. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4053. if event.button == 1:
  4054. if self.grid_status() == True:
  4055. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4056. else:
  4057. pos = pos_canvas
  4058. x = 0 - pos[0]
  4059. y = 0 - pos[1]
  4060. for obj in self.collection.get_list():
  4061. obj.offset((x,y))
  4062. self.object_changed.emit(obj)
  4063. obj.plot()
  4064. # Update the object bounding box options
  4065. a, b, c, d = obj.bounds()
  4066. obj.options['xmin'] = a
  4067. obj.options['ymin'] = b
  4068. obj.options['xmax'] = c
  4069. obj.options['ymax'] = d
  4070. # self.plot_all(zoom=False)
  4071. self.inform.emit(_('[success] Origin set ...'))
  4072. self.plotcanvas.fit_view()
  4073. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4074. self.should_we_save = True
  4075. def on_selectall(self):
  4076. self.report_usage("on_selectall()")
  4077. # delete the possible selection box around a possible selected object
  4078. self.delete_selection_shape()
  4079. for name in self.collection.get_names():
  4080. self.collection.set_active(name)
  4081. curr_sel_obj = self.collection.get_by_name(name)
  4082. # create the selection box around the selected object
  4083. if self.defaults['global_selection_shape'] is True:
  4084. self.draw_selection_shape(curr_sel_obj)
  4085. def on_preferences(self):
  4086. # add the tab if it was closed
  4087. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4088. # delete the absolute and relative position and messages in the infobar
  4089. self.ui.position_label.setText("")
  4090. self.ui.rel_position_label.setText("")
  4091. # Switch plot_area to preferences page
  4092. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4093. self.ui.show()
  4094. def on_flipy(self):
  4095. self.report_usage("on_flipy()")
  4096. obj_list = self.collection.get_selected()
  4097. xminlist = []
  4098. yminlist = []
  4099. xmaxlist = []
  4100. ymaxlist = []
  4101. if not obj_list:
  4102. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4103. else:
  4104. try:
  4105. # first get a bounding box to fit all
  4106. for obj in obj_list:
  4107. xmin, ymin, xmax, ymax = obj.bounds()
  4108. xminlist.append(xmin)
  4109. yminlist.append(ymin)
  4110. xmaxlist.append(xmax)
  4111. ymaxlist.append(ymax)
  4112. # get the minimum x,y and maximum x,y for all objects selected
  4113. xminimal = min(xminlist)
  4114. yminimal = min(yminlist)
  4115. xmaximal = max(xmaxlist)
  4116. ymaximal = max(ymaxlist)
  4117. px = 0.5 * (xminimal + xmaximal)
  4118. py = 0.5 * (yminimal + ymaximal)
  4119. # execute mirroring
  4120. for obj in obj_list:
  4121. obj.mirror('X', [px, py])
  4122. obj.plot()
  4123. self.object_changed.emit(obj)
  4124. self.inform.emit(_("[success] Flip on Y axis done."))
  4125. except Exception as e:
  4126. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4127. return
  4128. def on_flipx(self):
  4129. self.report_usage("on_flipx()")
  4130. obj_list = self.collection.get_selected()
  4131. xminlist = []
  4132. yminlist = []
  4133. xmaxlist = []
  4134. ymaxlist = []
  4135. if not obj_list:
  4136. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4137. else:
  4138. try:
  4139. # first get a bounding box to fit all
  4140. for obj in obj_list:
  4141. xmin, ymin, xmax, ymax = obj.bounds()
  4142. xminlist.append(xmin)
  4143. yminlist.append(ymin)
  4144. xmaxlist.append(xmax)
  4145. ymaxlist.append(ymax)
  4146. # get the minimum x,y and maximum x,y for all objects selected
  4147. xminimal = min(xminlist)
  4148. yminimal = min(yminlist)
  4149. xmaximal = max(xmaxlist)
  4150. ymaximal = max(ymaxlist)
  4151. px = 0.5 * (xminimal + xmaximal)
  4152. py = 0.5 * (yminimal + ymaximal)
  4153. # execute mirroring
  4154. for obj in obj_list:
  4155. obj.mirror('Y', [px, py])
  4156. obj.plot()
  4157. self.object_changed.emit(obj)
  4158. self.inform.emit(_("[success] Flip on X axis done."))
  4159. except Exception as e:
  4160. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4161. return
  4162. def on_rotate(self, silent=False, preset=None):
  4163. self.report_usage("on_rotate()")
  4164. obj_list = self.collection.get_selected()
  4165. xminlist = []
  4166. yminlist = []
  4167. xmaxlist = []
  4168. ymaxlist = []
  4169. if not obj_list:
  4170. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4171. else:
  4172. if silent is False:
  4173. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4174. min=-360, max=360, decimals=4,
  4175. init_val=float(self.defaults['tools_transform_rotate']))
  4176. num, ok = rotatebox.get_value()
  4177. else:
  4178. num = preset
  4179. ok = True
  4180. if ok:
  4181. try:
  4182. # first get a bounding box to fit all
  4183. for obj in obj_list:
  4184. xmin, ymin, xmax, ymax = obj.bounds()
  4185. xminlist.append(xmin)
  4186. yminlist.append(ymin)
  4187. xmaxlist.append(xmax)
  4188. ymaxlist.append(ymax)
  4189. # get the minimum x,y and maximum x,y for all objects selected
  4190. xminimal = min(xminlist)
  4191. yminimal = min(yminlist)
  4192. xmaximal = max(xmaxlist)
  4193. ymaximal = max(ymaxlist)
  4194. px = 0.5 * (xminimal + xmaximal)
  4195. py = 0.5 * (yminimal + ymaximal)
  4196. for sel_obj in obj_list:
  4197. sel_obj.rotate(-float(num), point=(px, py))
  4198. sel_obj.plot()
  4199. self.object_changed.emit(sel_obj)
  4200. self.inform.emit(_("[success] Rotation done."))
  4201. except Exception as e:
  4202. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4203. return
  4204. def on_skewx(self):
  4205. self.report_usage("on_skewx()")
  4206. obj_list = self.collection.get_selected()
  4207. xminlist = []
  4208. yminlist = []
  4209. if not obj_list:
  4210. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4211. else:
  4212. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4213. min=-360, max=360, decimals=4,
  4214. init_val=float(self.defaults['tools_transform_skew_x']))
  4215. num, ok = skewxbox.get_value()
  4216. if ok:
  4217. # first get a bounding box to fit all
  4218. for obj in obj_list:
  4219. xmin, ymin, xmax, ymax = obj.bounds()
  4220. xminlist.append(xmin)
  4221. yminlist.append(ymin)
  4222. # get the minimum x,y and maximum x,y for all objects selected
  4223. xminimal = min(xminlist)
  4224. yminimal = min(yminlist)
  4225. for obj in obj_list:
  4226. obj.skew(num, 0, point=(xminimal, yminimal))
  4227. obj.plot()
  4228. self.object_changed.emit(obj)
  4229. self.inform.emit(_("[success] Skew on X axis done."))
  4230. def on_skewy(self):
  4231. self.report_usage("on_skewy()")
  4232. obj_list = self.collection.get_selected()
  4233. xminlist = []
  4234. yminlist = []
  4235. if not obj_list:
  4236. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4237. else:
  4238. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4239. min=-360, max=360, decimals=4,
  4240. init_val=float(self.defaults['tools_transform_skew_y']))
  4241. num, ok = skewybox.get_value()
  4242. if ok:
  4243. # first get a bounding box to fit all
  4244. for obj in obj_list:
  4245. xmin, ymin, xmax, ymax = obj.bounds()
  4246. xminlist.append(xmin)
  4247. yminlist.append(ymin)
  4248. # get the minimum x,y and maximum x,y for all objects selected
  4249. xminimal = min(xminlist)
  4250. yminimal = min(yminlist)
  4251. for obj in obj_list:
  4252. obj.skew(0, num, point=(xminimal, yminimal))
  4253. obj.plot()
  4254. self.object_changed.emit(obj)
  4255. self.inform.emit(_("[success] Skew on Y axis done."))
  4256. def delete_first_selected(self):
  4257. # Keep this for later
  4258. try:
  4259. name = self.collection.get_active().options["name"]
  4260. except AttributeError:
  4261. self.log.debug("Nothing selected for deletion")
  4262. return
  4263. # Remove plot
  4264. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4265. # self.plotcanvas.auto_adjust_axes()
  4266. # Clear form
  4267. self.setup_component_editor()
  4268. # Remove from dictionary
  4269. self.collection.delete_active()
  4270. self.inform.emit("Object deleted: %s" % name)
  4271. def on_plots_updated(self):
  4272. """
  4273. Callback used to report when the plots have changed.
  4274. Adjust axes and zooms to fit.
  4275. :return: None
  4276. """
  4277. # self.plotcanvas.auto_adjust_axes()
  4278. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4279. self.on_zoom_fit(None)
  4280. self.collection.update_view()
  4281. # TODO: Rework toolbar 'clear', 'replot' functions
  4282. def on_toolbar_replot(self):
  4283. """
  4284. Callback for toolbar button. Re-plots all objects.
  4285. :return: None
  4286. """
  4287. self.report_usage("on_toolbar_replot")
  4288. self.log.debug("on_toolbar_replot()")
  4289. try:
  4290. self.collection.get_active().read_form()
  4291. except AttributeError:
  4292. self.log.debug("on_toolbar_replot(): AttributeError")
  4293. pass
  4294. self.plot_all()
  4295. def on_row_activated(self, index):
  4296. if index.isValid():
  4297. if index.internalPointer().parent_item != self.collection.root_item:
  4298. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4299. def grid_status(self):
  4300. if self.ui.grid_snap_btn.isChecked():
  4301. return 1
  4302. else:
  4303. return 0
  4304. def populate_cmenu_grids(self):
  4305. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4306. self.ui.cmenu_gridmenu.clear()
  4307. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4308. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4309. grid_toggle.setCheckable(True)
  4310. if self.grid_status():
  4311. grid_toggle.setChecked(True)
  4312. else:
  4313. grid_toggle.setChecked(False)
  4314. self.ui.cmenu_gridmenu.addSeparator()
  4315. for grid in sorted_list:
  4316. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4317. action.triggered.connect(self.set_grid)
  4318. self.ui.cmenu_gridmenu.addSeparator()
  4319. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4320. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4321. grid_add.triggered.connect(self.on_grid_add)
  4322. grid_delete.triggered.connect(self.on_grid_delete)
  4323. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4324. def set_grid(self):
  4325. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4326. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4327. def on_grid_add(self):
  4328. # ## Current application units in lower Case
  4329. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4330. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4331. text=_('Enter a Grid Value:'),
  4332. min=0.0000, max=99.9999, decimals=4)
  4333. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4334. val, ok = grid_add_popup.get_value()
  4335. if ok:
  4336. if float(val) == 0:
  4337. self.inform.emit(
  4338. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4339. return
  4340. else:
  4341. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4342. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4343. self.inform.emit(
  4344. _("[success] New Grid added ..."))
  4345. else:
  4346. self.inform.emit(
  4347. _("[WARNING_NOTCL] Grid already exists ..."))
  4348. else:
  4349. self.inform.emit(
  4350. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4351. def on_grid_delete(self):
  4352. # ## Current application units in lower Case
  4353. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4354. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4355. text='Enter a Grid Value:',
  4356. min=0.0000, max=99.9999, decimals=4)
  4357. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4358. val, ok = grid_del_popup.get_value()
  4359. if ok:
  4360. if float(val) == 0:
  4361. self.inform.emit(
  4362. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4363. return
  4364. else:
  4365. try:
  4366. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4367. except ValueError:
  4368. self.inform.emit(
  4369. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4370. return
  4371. self.inform.emit(
  4372. _("[success] Grid Value deleted ..."))
  4373. else:
  4374. self.inform.emit(
  4375. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4376. def on_shortcut_list(self):
  4377. self.report_usage("on_shortcut_list()")
  4378. # add the tab if it was closed
  4379. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4380. # delete the absolute and relative position and messages in the infobar
  4381. self.ui.position_label.setText("")
  4382. self.ui.rel_position_label.setText("")
  4383. # Switch plot_area to preferences page
  4384. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4385. self.ui.show()
  4386. def on_select_tab(self, name):
  4387. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4388. if self.ui.splitter.sizes()[0] == 0:
  4389. self.ui.splitter.setSizes([1, 1])
  4390. else:
  4391. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4392. self.ui.splitter.setSizes([0, 1])
  4393. if name == 'project':
  4394. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4395. elif name == 'selected':
  4396. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4397. elif name == 'tool':
  4398. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4399. def on_copy_name(self):
  4400. self.report_usage("on_copy_name()")
  4401. obj = self.collection.get_active()
  4402. try:
  4403. name = obj.options["name"]
  4404. except AttributeError:
  4405. log.debug("on_copy_name() --> No object selected to copy it's name")
  4406. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4407. return
  4408. self.clipboard.setText(name)
  4409. self.inform.emit(_("Name copied on clipboard ..."))
  4410. def on_mouse_click_over_plot(self, event):
  4411. """
  4412. Default actions are:
  4413. :param event: Contains information about the event, like which button
  4414. was clicked, the pixel coordinates and the axes coordinates.
  4415. :return: None
  4416. """
  4417. self.pos = []
  4418. # So it can receive key presses
  4419. self.plotcanvas.vispy_canvas.native.setFocus()
  4420. # Set the mouse button for panning
  4421. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4422. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4423. if self.grid_status() == True:
  4424. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4425. self.app_cursor.enabled = True
  4426. else:
  4427. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4428. self.app_cursor.enabled = False
  4429. try:
  4430. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4431. if event.button == 1:
  4432. # Reset here the relative coordinates so there is a new reference on the click position
  4433. if self.rel_point1 is None:
  4434. self.rel_point1 = self.pos
  4435. else:
  4436. self.rel_point2 = copy(self.rel_point1)
  4437. self.rel_point1 = self.pos
  4438. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4439. if modifiers == QtCore.Qt.ShiftModifier:
  4440. # do not auto open the Project Tab
  4441. self.click_noproject = True
  4442. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4443. return
  4444. self.on_mouse_move_over_plot(event, origin_click=True)
  4445. except Exception as e:
  4446. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4447. def on_double_click_over_plot(self, event):
  4448. self.doubleclick = True
  4449. def on_mouse_move_over_plot(self, event, origin_click=None):
  4450. """
  4451. Callback for the mouse motion event over the plot.
  4452. :param event: Contains information about the event.
  4453. :param origin_click
  4454. :return: None
  4455. """
  4456. # So it can receive key presses
  4457. self.plotcanvas.vispy_canvas.native.setFocus()
  4458. self.pos_jump = event.pos
  4459. self.ui.popMenu.mouse_is_panning = False
  4460. if origin_click != True:
  4461. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4462. if event.button == 2 and event.is_dragging == 1:
  4463. self.ui.popMenu.mouse_is_panning = True
  4464. return
  4465. if self.rel_point1 is not None:
  4466. try: # May fail in case mouse not within axes
  4467. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4468. if self.grid_status():
  4469. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4470. self.app_cursor.enabled = True
  4471. # Update cursor
  4472. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4473. else:
  4474. pos = (pos_canvas[0], pos_canvas[1])
  4475. self.app_cursor.enabled = False
  4476. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4477. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4478. dx = pos[0] - self.rel_point1[0]
  4479. dy = pos[1] - self.rel_point1[1]
  4480. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4481. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4482. self.mouse = [pos[0], pos[1]]
  4483. # if the mouse is moved and the LMB is clicked then the action is a selection
  4484. if event.is_dragging == 1 and event.button == 1:
  4485. self.delete_selection_shape()
  4486. if dx < 0:
  4487. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4488. face_color=self.defaults['global_alt_sel_fill'])
  4489. self.selection_type = False
  4490. else:
  4491. self.draw_moving_selection_shape(self.pos, pos)
  4492. self.selection_type = True
  4493. # hover effect - enabled in Preferences -> General -> GUI Settings
  4494. if self.defaults['global_hover']:
  4495. for obj in self.collection.get_list():
  4496. try:
  4497. # select the object(s) only if it is enabled (plotted)
  4498. if obj.options['plot']:
  4499. if obj not in self.collection.get_selected():
  4500. poly_obj = Polygon(
  4501. [(obj.options['xmin'], obj.options['ymin']),
  4502. (obj.options['xmax'], obj.options['ymin']),
  4503. (obj.options['xmax'], obj.options['ymax']),
  4504. (obj.options['xmin'], obj.options['ymax'])]
  4505. )
  4506. if Point(pos).within(poly_obj):
  4507. if obj.isHovering is False:
  4508. obj.isHovering = True
  4509. obj.notHovering = True
  4510. # create the selection box around the selected object
  4511. self.draw_hover_shape(obj, color='#d1e0e0')
  4512. else:
  4513. if obj.notHovering is True:
  4514. obj.notHovering = False
  4515. obj.isHovering = False
  4516. self.delete_hover_shape()
  4517. except:
  4518. # the Exception here will happen if we try to select on screen and we have an
  4519. # newly (and empty) just created Geometry or Excellon object that do not have the
  4520. # xmin, xmax, ymin, ymax options.
  4521. # In this case poly_obj creation (see above) will fail
  4522. pass
  4523. except:
  4524. self.ui.position_label.setText("")
  4525. self.ui.rel_position_label.setText("")
  4526. self.mouse = None
  4527. def on_mouse_click_release_over_plot(self, event):
  4528. """
  4529. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4530. and has been registered in ''self.__init__()''.
  4531. :param event: contains information about the event.
  4532. :return:
  4533. """
  4534. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4535. if self.grid_status():
  4536. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4537. else:
  4538. pos = (pos_canvas[0], pos_canvas[1])
  4539. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4540. # canvas menu
  4541. try:
  4542. if event.button == 2: # right click
  4543. if self.ui.popMenu.mouse_is_panning is False:
  4544. self.cursor = QtGui.QCursor()
  4545. self.populate_cmenu_grids()
  4546. self.ui.popMenu.popup(self.cursor.pos())
  4547. except Exception as e:
  4548. log.warning("Error: %s" % str(e))
  4549. return
  4550. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4551. # selection and then select a type of selection ("enclosing" or "touching")
  4552. try:
  4553. if event.button == 1: # left click
  4554. if self.doubleclick is True:
  4555. self.doubleclick = False
  4556. if self.collection.get_selected():
  4557. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4558. if self.ui.splitter.sizes()[0] == 0:
  4559. self.ui.splitter.setSizes([1, 1])
  4560. # delete the selection shape(S) as it may be in the way
  4561. self.delete_selection_shape()
  4562. self.delete_hover_shape()
  4563. else:
  4564. if self.selection_type is not None:
  4565. self.selection_area_handler(self.pos, pos, self.selection_type)
  4566. self.selection_type = None
  4567. else:
  4568. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4569. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4570. # deselect, and if it's not selected then it will be selected
  4571. if modifiers == QtCore.Qt.ControlModifier:
  4572. # If there is no active command (self.command_active is None) then we check if we clicked
  4573. # on a object by checking the bounding limits against mouse click position
  4574. if self.command_active is None:
  4575. self.select_objects(key='CTRL')
  4576. self.delete_hover_shape()
  4577. else:
  4578. # If there is no active command (self.command_active is None) then we check if we clicked
  4579. # on a object by checking the bounding limits against mouse click position
  4580. if self.command_active is None:
  4581. self.select_objects()
  4582. self.delete_hover_shape()
  4583. except Exception as e:
  4584. log.warning("Error: %s" % str(e))
  4585. return
  4586. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4587. """
  4588. :param start_pos: mouse position when the selection LMB click was done
  4589. :param end_pos: mouse position when the left mouse button is released
  4590. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4591. :return:
  4592. """
  4593. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4594. self.delete_selection_shape()
  4595. for obj in self.collection.get_list():
  4596. try:
  4597. # select the object(s) only if it is enabled (plotted)
  4598. if obj.options['plot']:
  4599. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4600. (obj.options['xmax'], obj.options['ymin']),
  4601. (obj.options['xmax'], obj.options['ymax']),
  4602. (obj.options['xmin'], obj.options['ymax'])])
  4603. if sel_type is True:
  4604. if poly_obj.within(poly_selection):
  4605. # create the selection box around the selected object
  4606. if self.defaults['global_selection_shape'] is True:
  4607. self.draw_selection_shape(obj)
  4608. self.collection.set_active(obj.options['name'])
  4609. else:
  4610. if poly_selection.intersects(poly_obj):
  4611. # create the selection box around the selected object
  4612. if self.defaults['global_selection_shape'] is True:
  4613. self.draw_selection_shape(obj)
  4614. self.collection.set_active(obj.options['name'])
  4615. except Exception as e:
  4616. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4617. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4618. # In this case poly_obj creation (see above) will fail
  4619. log.debug("App.selection_area_handler() --> %s" % str(e))
  4620. def select_objects(self, key=None):
  4621. # list where we store the overlapped objects under our mouse left click position
  4622. objects_under_the_click_list = []
  4623. # Populate the list with the overlapped objects on the click position
  4624. curr_x, curr_y = self.pos
  4625. for obj in self.all_objects_list:
  4626. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4627. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4628. if obj.options['name'] not in objects_under_the_click_list:
  4629. if obj.options['plot']:
  4630. # add objects to the objects_under_the_click list only if the object is plotted
  4631. # (active and not disabled)
  4632. objects_under_the_click_list.append(obj.options['name'])
  4633. try:
  4634. # If there is no element in the overlapped objects list then make everyone inactive
  4635. # because we selected "nothing"
  4636. if not objects_under_the_click_list:
  4637. self.collection.set_all_inactive()
  4638. # delete the possible selection box around a possible selected object
  4639. self.delete_selection_shape()
  4640. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4641. # only when working on App
  4642. if self.call_source == 'app':
  4643. if self.click_noproject is False:
  4644. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4645. else:
  4646. # restore auto open the Project Tab
  4647. self.click_noproject = False
  4648. # delete any text in the status bar, implicitly the last object name that was selected
  4649. self.inform.emit("")
  4650. else:
  4651. self.call_source = 'app'
  4652. else:
  4653. # case when there is only an object under the click and we toggle it
  4654. if len(objects_under_the_click_list) == 1:
  4655. if self.collection.get_active() is None :
  4656. self.collection.set_active(objects_under_the_click_list[0])
  4657. # create the selection box around the selected object
  4658. curr_sel_obj = self.collection.get_active()
  4659. if self.defaults['global_selection_shape'] is True:
  4660. self.draw_selection_shape(curr_sel_obj)
  4661. # self.inform.emit('[selected] %s: %s selected' %
  4662. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4663. if curr_sel_obj.kind == 'gerber':
  4664. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4665. color='green', name=str(curr_sel_obj.options['name'])))
  4666. elif curr_sel_obj.kind == 'excellon':
  4667. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4668. color='brown', name=str(curr_sel_obj.options['name'])))
  4669. elif curr_sel_obj.kind == 'cncjob':
  4670. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4671. color='blue', name=str(curr_sel_obj.options['name'])))
  4672. elif curr_sel_obj.kind == 'geometry':
  4673. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4674. color='red', name=str(curr_sel_obj.options['name'])))
  4675. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4676. self.collection.set_all_inactive()
  4677. self.delete_selection_shape()
  4678. self.collection.set_active(objects_under_the_click_list[0])
  4679. # create the selection box around the selected object
  4680. curr_sel_obj = self.collection.get_active()
  4681. if self.defaults['global_selection_shape'] is True:
  4682. self.draw_selection_shape(curr_sel_obj)
  4683. # self.inform.emit('[selected] %s: %s selected' %
  4684. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4685. if curr_sel_obj.kind == 'gerber':
  4686. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4687. color='green', name=str(curr_sel_obj.options['name'])))
  4688. elif curr_sel_obj.kind == 'excellon':
  4689. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4690. color='brown', name=str(curr_sel_obj.options['name'])))
  4691. elif curr_sel_obj.kind == 'cncjob':
  4692. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4693. color='blue', name=str(curr_sel_obj.options['name'])))
  4694. elif curr_sel_obj.kind == 'geometry':
  4695. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4696. color='red', name=str(curr_sel_obj.options['name'])))
  4697. else:
  4698. self.collection.set_all_inactive()
  4699. self.delete_selection_shape()
  4700. if self.call_source == 'app':
  4701. # delete any text in the status bar, implicitly the last object name that was selected
  4702. self.inform.emit("")
  4703. else:
  4704. self.call_source = 'app'
  4705. else:
  4706. # If there is no selected object
  4707. # make active the first element of the overlapped objects list
  4708. if self.collection.get_active() is None:
  4709. self.collection.set_active(objects_under_the_click_list[0])
  4710. name_sel_obj = self.collection.get_active().options['name']
  4711. # In case that there is a selected object but it is not in the overlapped object list
  4712. # make that object inactive and activate the first element in the overlapped object list
  4713. if name_sel_obj not in objects_under_the_click_list:
  4714. self.collection.set_inactive(name_sel_obj)
  4715. name_sel_obj = objects_under_the_click_list[0]
  4716. self.collection.set_active(name_sel_obj)
  4717. else:
  4718. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4719. self.collection.set_all_inactive()
  4720. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4721. len(objects_under_the_click_list)])
  4722. curr_sel_obj = self.collection.get_active()
  4723. # delete the possible selection box around a possible selected object
  4724. self.delete_selection_shape()
  4725. # create the selection box around the selected object
  4726. if self.defaults['global_selection_shape'] is True:
  4727. self.draw_selection_shape(curr_sel_obj)
  4728. # self.inform.emit('[selected] %s: %s selected' %
  4729. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4730. if curr_sel_obj.kind == 'gerber':
  4731. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4732. color='green', name=str(curr_sel_obj.options['name'])))
  4733. elif curr_sel_obj.kind == 'excellon':
  4734. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4735. color='brown', name=str(curr_sel_obj.options['name'])))
  4736. elif curr_sel_obj.kind == 'cncjob':
  4737. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4738. color='blue', name=str(curr_sel_obj.options['name'])))
  4739. elif curr_sel_obj.kind == 'geometry':
  4740. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4741. color='red', name=str(curr_sel_obj.options['name'])))
  4742. # for obj in self.collection.get_list():
  4743. # obj.plot()
  4744. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4745. # TODO: on selected objects change the object colors and do not draw the selection box
  4746. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4747. except Exception as e:
  4748. log.error("[ERROR] Something went bad. %s" % str(e))
  4749. return
  4750. def delete_hover_shape(self):
  4751. self.hover_shapes.clear()
  4752. self.hover_shapes.redraw()
  4753. def draw_hover_shape(self, sel_obj, color=None):
  4754. """
  4755. :param sel_obj: the object for which the hover shape must be drawn
  4756. :return:
  4757. """
  4758. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4759. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4760. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4761. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4762. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4763. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4764. hover_rect = hover_rect.buffer(-0.1)
  4765. hover_rect = hover_rect.buffer(0.2)
  4766. else:
  4767. hover_rect = hover_rect.buffer(-0.00393)
  4768. hover_rect = hover_rect.buffer(0.00787)
  4769. if color:
  4770. face = Color(color)
  4771. face.alpha = 0.2
  4772. outline = Color(color, alpha=0.8)
  4773. else:
  4774. face = Color(self.defaults['global_sel_fill'])
  4775. face.alpha = 0.2
  4776. outline = self.defaults['global_sel_line']
  4777. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4778. def delete_selection_shape(self):
  4779. self.move_tool.sel_shapes.clear()
  4780. self.move_tool.sel_shapes.redraw()
  4781. def draw_selection_shape(self, sel_obj, color=None):
  4782. """
  4783. :param sel_obj: the object for which the selection shape must be drawn
  4784. :return:
  4785. """
  4786. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4787. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4788. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4789. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4790. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4791. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4792. sel_rect = sel_rect.buffer(-0.1)
  4793. sel_rect = sel_rect.buffer(0.2)
  4794. else:
  4795. sel_rect = sel_rect.buffer(-0.00393)
  4796. sel_rect = sel_rect.buffer(0.00787)
  4797. if color:
  4798. face = Color(color, alpha=0.2)
  4799. outline = Color(color, alpha=0.8)
  4800. else:
  4801. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4802. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4803. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4804. face_color=face, update=True, layer=0, tolerance=None))
  4805. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4806. """
  4807. :param old_coords: old coordinates
  4808. :param coords: new coordinates
  4809. :return:
  4810. """
  4811. if 'color' in kwargs:
  4812. color = kwargs['color']
  4813. else:
  4814. color = self.defaults['global_sel_line']
  4815. if 'face_color' in kwargs:
  4816. face_color = kwargs['face_color']
  4817. else:
  4818. face_color = self.defaults['global_sel_fill']
  4819. x0, y0 = old_coords
  4820. x1, y1 = coords
  4821. pt1 = (x0, y0)
  4822. pt2 = (x1, y0)
  4823. pt3 = (x1, y1)
  4824. pt4 = (x0, y1)
  4825. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4826. color_t = Color(face_color)
  4827. color_t.alpha = 0.3
  4828. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4829. layer=0, tolerance=None)
  4830. def on_file_new_click(self):
  4831. if self.collection.get_list() and self.should_we_save:
  4832. msgbox = QtWidgets.QMessageBox()
  4833. # msgbox.setText("<B>Save changes ...</B>")
  4834. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4835. "Creating a New project will delete them.\n"
  4836. "Do you want to Save the project?"))
  4837. msgbox.setWindowTitle(_("Save changes"))
  4838. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4839. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4840. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4841. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4842. msgbox.setDefaultButton(bt_yes)
  4843. msgbox.exec_()
  4844. response = msgbox.clickedButton()
  4845. if response == bt_yes:
  4846. self.on_file_saveprojectas()
  4847. elif response == bt_cancel:
  4848. return
  4849. elif response == bt_no:
  4850. self.on_file_new()
  4851. else:
  4852. self.on_file_new()
  4853. self.inform.emit(_("[success] New Project created..."))
  4854. def on_file_new(self):
  4855. """
  4856. Callback for menu item File->New. Returns the application to its
  4857. startup state. This method is thread-safe.
  4858. :return: None
  4859. """
  4860. self.report_usage("on_file_new")
  4861. # Remove everything from memory
  4862. App.log.debug("on_file_new()")
  4863. if self.call_source != 'app':
  4864. self.editor2object(cleanup=True)
  4865. # ## EDITOR section
  4866. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4867. self.exc_editor = FlatCAMExcEditor(self)
  4868. self.grb_editor = FlatCAMGrbEditor(self)
  4869. # Clear pool
  4870. self.clear_pool()
  4871. #delete shapes left drawn from mark shape_collections, if any
  4872. for obj in self.collection.get_list():
  4873. try:
  4874. obj.mark_shapes.enabled = False
  4875. obj.mark_shapes.clear(update=True)
  4876. except:
  4877. pass
  4878. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4879. self.init_tcl()
  4880. self.delete_selection_shape()
  4881. self.collection.delete_all()
  4882. self.setup_component_editor()
  4883. # Clear project filename
  4884. self.project_filename = None
  4885. # Load the application defaults
  4886. self.load_defaults(filename='current_defaults')
  4887. # Re-fresh project options
  4888. self.on_options_app2project()
  4889. # Init Tools
  4890. self.init_tools()
  4891. # Close any Tabs opened in the Plot Tab Area section
  4892. for index in range(self.ui.plot_tab_area.count()):
  4893. self.ui.plot_tab_area.closeTab(index)
  4894. # for whatever reason previous command does not close the last tab so I do it manually
  4895. self.ui.plot_tab_area.closeTab(0)
  4896. # # And then add again the Plot Area
  4897. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4898. self.ui.plot_tab_area.protectTab(0)
  4899. # take the focus of the Notebook on Project Tab.
  4900. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4901. def obj_properties(self):
  4902. self.report_usage("obj_properties()")
  4903. self.properties_tool.run(toggle=False)
  4904. def on_project_context_save(self):
  4905. obj = self.collection.get_active()
  4906. if type(obj) == FlatCAMGeometry:
  4907. self.on_file_exportdxf()
  4908. elif type(obj) == FlatCAMExcellon:
  4909. self.on_file_saveexcellon()
  4910. elif type(obj) == FlatCAMCNCjob:
  4911. obj.on_exportgcode_button_click()
  4912. elif type(obj) == FlatCAMGerber:
  4913. self.on_file_savegerber()
  4914. def obj_move(self):
  4915. self.report_usage("obj_move()")
  4916. self.move_tool.run(toggle=False)
  4917. def on_fileopengerber(self):
  4918. """
  4919. File menu callback for opening a Gerber.
  4920. :return: None
  4921. """
  4922. self.report_usage("on_fileopengerber")
  4923. App.log.debug("on_fileopengerber()")
  4924. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4925. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4926. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4927. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4928. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4929. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4930. "Allegro Files (*.art);;" \
  4931. "Mentor Files (*.pho *.gdo);;" \
  4932. "All Files (*.*)"
  4933. try:
  4934. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4935. directory=self.get_last_folder(), filter=_filter_)
  4936. except TypeError:
  4937. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4938. filenames = [str(filename) for filename in filenames]
  4939. if len(filenames) == 0:
  4940. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4941. else:
  4942. for filename in filenames:
  4943. if filename != '':
  4944. self.worker_task.emit({'fcn': self.open_gerber,
  4945. 'params': [filename]})
  4946. def on_fileopenexcellon(self):
  4947. """
  4948. File menu callback for opening an Excellon file.
  4949. :return: None
  4950. """
  4951. self.report_usage("on_fileopenexcellon")
  4952. App.log.debug("on_fileopenexcellon()")
  4953. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  4954. "All Files (*.*)"
  4955. try:
  4956. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4957. directory=self.get_last_folder(), filter=_filter_)
  4958. except TypeError:
  4959. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4960. filenames = [str(filename) for filename in filenames]
  4961. if len(filenames) == 0:
  4962. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4963. else:
  4964. for filename in filenames:
  4965. if filename != '':
  4966. self.worker_task.emit({'fcn': self.open_excellon,
  4967. 'params': [filename]})
  4968. def on_fileopengcode(self):
  4969. """
  4970. File menu call back for opening gcode.
  4971. :return: None
  4972. """
  4973. self.report_usage("on_fileopengcode")
  4974. App.log.debug("on_fileopengcode()")
  4975. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4976. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4977. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4978. "All Files (*.*)"
  4979. try:
  4980. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4981. directory=self.get_last_folder(), filter=_filter_)
  4982. except TypeError:
  4983. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4984. filenames = [str(filename) for filename in filenames]
  4985. if len(filenames) == 0:
  4986. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  4987. else:
  4988. for filename in filenames:
  4989. if filename != '':
  4990. self.worker_task.emit({'fcn': self.open_gcode,
  4991. 'params': [filename]})
  4992. def on_file_openproject(self):
  4993. """
  4994. File menu callback for opening a project.
  4995. :return: None
  4996. """
  4997. self.report_usage("on_file_openproject")
  4998. App.log.debug("on_file_openproject()")
  4999. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5000. try:
  5001. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5002. directory=self.get_last_folder(), filter=_filter_)
  5003. except TypeError:
  5004. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  5005. # The Qt methods above will return a QString which can cause problems later.
  5006. # So far json.dump() will fail to serialize it.
  5007. # TODO: Improve the serialization methods and remove this fix.
  5008. filename = str(filename)
  5009. if filename == "":
  5010. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5011. else:
  5012. # self.worker_task.emit({'fcn': self.open_project,
  5013. # 'params': [filename]})
  5014. # The above was failing because open_project() is not
  5015. # thread safe. The new_project()
  5016. self.open_project(filename)
  5017. def on_file_openconfig(self):
  5018. """
  5019. File menu callback for opening a config file.
  5020. :return: None
  5021. """
  5022. self.report_usage("on_file_openconfig")
  5023. App.log.debug("on_file_openconfig()")
  5024. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5025. try:
  5026. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5027. directory=self.data_path, filter=_filter_)
  5028. except TypeError:
  5029. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5030. filter = _filter_)
  5031. if filename == "":
  5032. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  5033. else:
  5034. self.open_config_file(filename)
  5035. def on_file_exportsvg(self):
  5036. """
  5037. Callback for menu item File->Export SVG.
  5038. :return: None
  5039. """
  5040. self.report_usage("on_file_exportsvg")
  5041. App.log.debug("on_file_exportsvg()")
  5042. obj = self.collection.get_active()
  5043. if obj is None:
  5044. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5045. msg = _("Please Select a Geometry object to export")
  5046. msgbox = QtWidgets.QMessageBox()
  5047. msgbox.setInformativeText(msg)
  5048. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5049. msgbox.setDefaultButton(bt_ok)
  5050. msgbox.exec_()
  5051. return
  5052. # Check for more compatible types and add as required
  5053. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  5054. and not isinstance(obj, FlatCAMExcellon)):
  5055. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5056. msgbox = QtWidgets.QMessageBox()
  5057. msgbox.setInformativeText(msg)
  5058. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5059. msgbox.setDefaultButton(bt_ok)
  5060. msgbox.exec_()
  5061. return
  5062. name = self.collection.get_active().options["name"]
  5063. filter = "SVG File (*.svg);;All Files (*.*)"
  5064. try:
  5065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5066. caption=_("Export SVG"),
  5067. directory=self.get_last_save_folder() + '/' + str(name),
  5068. filter=filter)
  5069. except TypeError:
  5070. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  5071. filename = str(filename)
  5072. if filename == "":
  5073. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5074. return
  5075. else:
  5076. self.export_svg(name, filename)
  5077. if self.defaults["global_open_style"] is False:
  5078. self.file_opened.emit("SVG", filename)
  5079. self.file_saved.emit("SVG", filename)
  5080. def on_file_exportpng(self):
  5081. self.report_usage("on_file_exportpng")
  5082. App.log.debug("on_file_exportpng()")
  5083. self.date = str(datetime.today()).rpartition('.')[0]
  5084. self.date = ''.join(c for c in self.date if c not in ':-')
  5085. self.date = self.date.replace(' ', '_')
  5086. image = _screenshot()
  5087. data = np.asarray(image)
  5088. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5089. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5090. return
  5091. filter_ = "PNG File (*.png);;All Files (*.*)"
  5092. try:
  5093. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5094. caption=_("Export PNG Image"),
  5095. directory=self.get_last_save_folder() + '/png_' + self.date,
  5096. filter=filter_)
  5097. except TypeError:
  5098. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5099. filename = str(filename)
  5100. if filename == "":
  5101. self.inform.emit(_("Export PNG cancelled."))
  5102. return
  5103. else:
  5104. write_png(filename, data)
  5105. if self.defaults["global_open_style"] is False:
  5106. self.file_opened.emit("png", filename)
  5107. self.file_saved.emit("png", filename)
  5108. def on_file_savegerber(self):
  5109. """
  5110. Callback for menu item File->Export Gerber.
  5111. :return: None
  5112. """
  5113. self.report_usage("on_file_savegerber")
  5114. App.log.debug("on_file_savegerber()")
  5115. obj = self.collection.get_active()
  5116. if obj is None:
  5117. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5118. return
  5119. # Check for more compatible types and add as required
  5120. if not isinstance(obj, FlatCAMGerber):
  5121. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5122. return
  5123. name = self.collection.get_active().options["name"]
  5124. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5125. try:
  5126. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5127. caption="Save Gerber source file",
  5128. directory=self.get_last_save_folder() + '/' + name,
  5129. filter=filter)
  5130. except TypeError:
  5131. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  5132. filename = str(filename)
  5133. if filename == "":
  5134. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5135. return
  5136. else:
  5137. self.save_source_file(name, filename)
  5138. if self.defaults["global_open_style"] is False:
  5139. self.file_opened.emit("Gerber", filename)
  5140. self.file_saved.emit("Gerber", filename)
  5141. def on_file_saveexcellon(self):
  5142. """
  5143. Callback for menu item File->Export Gerber.
  5144. :return: None
  5145. """
  5146. self.report_usage("on_file_saveexcellon")
  5147. App.log.debug("on_file_saveexcellon()")
  5148. obj = self.collection.get_active()
  5149. if obj is None:
  5150. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5151. return
  5152. # Check for more compatible types and add as required
  5153. if not isinstance(obj, FlatCAMExcellon):
  5154. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5155. return
  5156. name = self.collection.get_active().options["name"]
  5157. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5158. try:
  5159. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5160. caption=_("Save Excellon source file"),
  5161. directory=self.get_last_save_folder() + '/' + name,
  5162. filter=filter)
  5163. except TypeError:
  5164. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  5165. filename = str(filename)
  5166. if filename == "":
  5167. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5168. return
  5169. else:
  5170. self.save_source_file(name, filename)
  5171. if self.defaults["global_open_style"] is False:
  5172. self.file_opened.emit("Excellon", filename)
  5173. self.file_saved.emit("Excellon", filename)
  5174. def on_file_exportexcellon(self):
  5175. """
  5176. Callback for menu item File->Export->Excellon.
  5177. :return: None
  5178. """
  5179. self.report_usage("on_file_exportexcellon")
  5180. App.log.debug("on_file_exportexcellon()")
  5181. obj = self.collection.get_active()
  5182. if obj is None:
  5183. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5184. return
  5185. # Check for more compatible types and add as required
  5186. if not isinstance(obj, FlatCAMExcellon):
  5187. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5188. return
  5189. name = self.collection.get_active().options["name"]
  5190. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5191. try:
  5192. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5193. caption=_("Export Excellon"),
  5194. directory=self.get_last_save_folder() + '/' + name,
  5195. filter=filter)
  5196. except TypeError:
  5197. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  5198. filename = str(filename)
  5199. if filename == "":
  5200. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5201. return
  5202. else:
  5203. self.export_excellon(name, filename)
  5204. if self.defaults["global_open_style"] is False:
  5205. self.file_opened.emit("Excellon", filename)
  5206. self.file_saved.emit("Excellon", filename)
  5207. def on_file_exportgerber(self):
  5208. """
  5209. Callback for menu item File->Export->Gerber.
  5210. :return: None
  5211. """
  5212. self.report_usage("on_file_exportgerber")
  5213. App.log.debug("on_file_exportgerber()")
  5214. obj = self.collection.get_active()
  5215. if obj is None:
  5216. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5217. return
  5218. # Check for more compatible types and add as required
  5219. if not isinstance(obj, FlatCAMGerber):
  5220. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5221. return
  5222. name = self.collection.get_active().options["name"]
  5223. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5224. try:
  5225. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5226. caption=_("Export Gerber"),
  5227. directory=self.get_last_save_folder() + '/' + name,
  5228. filter=_filter_)
  5229. except TypeError:
  5230. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5231. filename = str(filename)
  5232. if filename == "":
  5233. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5234. return
  5235. else:
  5236. self.export_gerber(name, filename)
  5237. if self.defaults["global_open_style"] is False:
  5238. self.file_opened.emit("Gerber", filename)
  5239. self.file_saved.emit("Gerber", filename)
  5240. def on_file_exportdxf(self):
  5241. """
  5242. Callback for menu item File->Export DXF.
  5243. :return: None
  5244. """
  5245. self.report_usage("on_file_exportdxf")
  5246. App.log.debug("on_file_exportdxf()")
  5247. obj = self.collection.get_active()
  5248. if obj is None:
  5249. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5250. msg = _("Please Select a Geometry object to export")
  5251. msgbox = QtWidgets.QMessageBox()
  5252. msgbox.setInformativeText(msg)
  5253. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5254. msgbox.setDefaultButton(bt_ok)
  5255. msgbox.exec_()
  5256. return
  5257. # Check for more compatible types and add as required
  5258. if not isinstance(obj, FlatCAMGeometry):
  5259. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5260. msgbox = QtWidgets.QMessageBox()
  5261. msgbox.setInformativeText(msg)
  5262. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5263. msgbox.setDefaultButton(bt_ok)
  5264. msgbox.exec_()
  5265. return
  5266. name = self.collection.get_active().options["name"]
  5267. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5268. try:
  5269. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5270. caption=_("Export DXF"),
  5271. directory=self.get_last_save_folder() + '/' + name,
  5272. filter=_filter_)
  5273. except TypeError:
  5274. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5275. filter=_filter_)
  5276. filename = str(filename)
  5277. if filename == "":
  5278. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5279. return
  5280. else:
  5281. self.export_dxf(name, filename)
  5282. if self.defaults["global_open_style"] is False:
  5283. self.file_opened.emit("DXF", filename)
  5284. self.file_saved.emit("DXF", filename)
  5285. def on_file_importsvg(self, type_of_obj):
  5286. """
  5287. Callback for menu item File->Import SVG.
  5288. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5289. :type type_of_obj: str
  5290. :return: None
  5291. """
  5292. self.report_usage("on_file_importsvg")
  5293. App.log.debug("on_file_importsvg()")
  5294. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5295. try:
  5296. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5297. directory=self.get_last_folder(), filter=_filter_)
  5298. except TypeError:
  5299. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5300. filter=_filter_)
  5301. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5302. type_of_obj = "geometry"
  5303. filenames = [str(filename) for filename in filenames]
  5304. if len(filenames) == 0:
  5305. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5306. else:
  5307. for filename in filenames:
  5308. if filename != '':
  5309. self.worker_task.emit({'fcn': self.import_svg,
  5310. 'params': [filename, type_of_obj]})
  5311. def on_file_importdxf(self, type_of_obj):
  5312. """
  5313. Callback for menu item File->Import DXF.
  5314. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5315. :type type_of_obj: str
  5316. :return: None
  5317. """
  5318. self.report_usage("on_file_importdxf")
  5319. App.log.debug("on_file_importdxf()")
  5320. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5321. try:
  5322. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5323. directory=self.get_last_folder(),
  5324. filter=_filter_)
  5325. except TypeError:
  5326. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5327. filter=_filter_)
  5328. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5329. type_of_obj = "geometry"
  5330. filenames = [str(filename) for filename in filenames]
  5331. if len(filenames) == 0:
  5332. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5333. else:
  5334. for filename in filenames:
  5335. if filename != '':
  5336. self.worker_task.emit({'fcn': self.import_dxf,
  5337. 'params': [filename, type_of_obj]})
  5338. # ################################################################################################################ ##
  5339. # # ## The following section has the functions that are displayed and call the Editor tab CNCJob Tab ############### ##
  5340. # ################################################################################################################ ##
  5341. def init_code_editor(self, name):
  5342. # Signals section
  5343. # Disconnect the old signals
  5344. self.ui.buttonOpen.clicked.disconnect()
  5345. self.ui.buttonSave.clicked.disconnect()
  5346. # add the tab if it was closed
  5347. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5348. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5349. # delete the absolute and relative position and messages in the infobar
  5350. self.ui.position_label.setText("")
  5351. self.ui.rel_position_label.setText("")
  5352. # first clear previous text in text editor (if any)
  5353. self.ui.code_editor.clear()
  5354. self.ui.code_editor.setReadOnly(False)
  5355. self.toggle_codeeditor = True
  5356. self.ui.code_editor.completer_enable = False
  5357. # Switch plot_area to CNCJob tab
  5358. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5359. def on_view_source(self):
  5360. try:
  5361. obj = self.collection.get_active()
  5362. except:
  5363. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5364. return 'fail'
  5365. # then append the text from GCode to the text editor
  5366. try:
  5367. file = StringIO(obj.source_file)
  5368. except AttributeError:
  5369. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5370. return 'fail'
  5371. if obj.kind == 'gerber':
  5372. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5373. elif obj.kind == 'excellon':
  5374. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5375. self.init_code_editor(name=_("Source Editor"))
  5376. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5377. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5378. try:
  5379. for line in file:
  5380. proc_line = str(line).strip('\n')
  5381. self.ui.code_editor.append(proc_line)
  5382. except Exception as e:
  5383. log.debug('App.on_view_source() -->%s' % str(e))
  5384. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5385. return
  5386. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5387. self.handleTextChanged()
  5388. self.ui.show()
  5389. def on_toggle_code_editor(self):
  5390. self.report_usage("on_toggle_code_editor()")
  5391. if self.toggle_codeeditor is False:
  5392. self.init_code_editor(name=_("Code Editor"))
  5393. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5394. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5395. else:
  5396. for idx in range(self.ui.plot_tab_area.count()):
  5397. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5398. self.ui.plot_tab_area.closeTab(idx)
  5399. break
  5400. self.toggle_codeeditor = False
  5401. def on_filenewscript(self):
  5402. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5403. self.init_code_editor(name=_("Script Editor"))
  5404. self.ui.code_editor.completer_enable = True
  5405. self.ui.code_editor.append(_(
  5406. "#\n"
  5407. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5408. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5409. "#\n\n"
  5410. "# FlatCAM commands list:\n"
  5411. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5412. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5413. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5414. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5415. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5416. "# WriteGCode\n"
  5417. "#\n\n"
  5418. ))
  5419. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5420. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5421. self.handleTextChanged()
  5422. self.ui.code_editor.show()
  5423. def on_fileopenscript(self):
  5424. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5425. try:
  5426. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5427. directory=self.get_last_folder(), filter=_filter_)
  5428. except TypeError:
  5429. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5430. # The Qt methods above will return a QString which can cause problems later.
  5431. # So far json.dump() will fail to serialize it.
  5432. # TODO: Improve the serialization methods and remove this fix.
  5433. filename = str(filename)
  5434. if filename == "":
  5435. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5436. else:
  5437. self.on_filenewscript()
  5438. try:
  5439. with open(filename, "r") as opened_script:
  5440. try:
  5441. for line in opened_script:
  5442. proc_line = str(line).strip('\n')
  5443. self.ui.code_editor.append(proc_line)
  5444. except Exception as e:
  5445. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5446. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5447. return
  5448. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5449. self.handleTextChanged()
  5450. self.ui.show()
  5451. except Exception as e:
  5452. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5453. def on_filerunscript(self, name=None):
  5454. """
  5455. File menu callback for loading and running a TCL script.
  5456. :return: None
  5457. """
  5458. self.report_usage("on_filerunscript")
  5459. App.log.debug("on_file_runscript()")
  5460. if name:
  5461. filename = name
  5462. else:
  5463. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5464. try:
  5465. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5466. directory=self.get_last_folder(), filter=_filter_)
  5467. except TypeError:
  5468. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5469. # The Qt methods above will return a QString which can cause problems later.
  5470. # So far json.dump() will fail to serialize it.
  5471. # TODO: Improve the serialization methods and remove this fix.
  5472. filename = str(filename)
  5473. if filename == "":
  5474. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5475. else:
  5476. try:
  5477. with open(filename, "r") as tcl_script:
  5478. cmd_line_shellfile_content = tcl_script.read()
  5479. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5480. except Exception as e:
  5481. log.debug("App.on_filerunscript() -> %s" % str(e))
  5482. sys.exit(2)
  5483. def on_file_saveproject(self):
  5484. """
  5485. Callback for menu item File->Save Project. Saves the project to
  5486. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5487. if set to None. The project is saved by calling ``self.save_project()``.
  5488. :return: None
  5489. """
  5490. self.report_usage("on_file_saveproject")
  5491. if self.project_filename is None:
  5492. self.on_file_saveprojectas()
  5493. else:
  5494. self.worker_task.emit({'fcn': self.save_project,
  5495. 'params': [self.project_filename]})
  5496. if self.defaults["global_open_style"] is False:
  5497. self.file_opened.emit("project", self.project_filename)
  5498. self.file_saved.emit("project", self.project_filename)
  5499. self.should_we_save = False
  5500. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5501. """
  5502. Callback for menu item File->Save Project As... Opens a file
  5503. chooser and saves the project to the given file via
  5504. ``self.save_project()``.
  5505. :return: None
  5506. """
  5507. self.report_usage("on_file_saveprojectas")
  5508. self.date = str(datetime.today()).rpartition('.')[0]
  5509. self.date = ''.join(c for c in self.date if c not in ':-')
  5510. self.date = self.date.replace(' ', '_')
  5511. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5512. try:
  5513. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5514. caption=_("Save Project As ..."),
  5515. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5516. filter=filter_)
  5517. except TypeError:
  5518. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5519. filename = str(filename)
  5520. if filename == '':
  5521. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5522. return
  5523. try:
  5524. f = open(filename, 'r')
  5525. f.close()
  5526. except IOError:
  5527. pass
  5528. if thread is True:
  5529. self.worker_task.emit({'fcn': self.save_project,
  5530. 'params': [filename, quit]})
  5531. else:
  5532. self.save_project(filename, quit)
  5533. # self.save_project(filename)
  5534. if self.defaults["global_open_style"] is False:
  5535. self.file_opened.emit("project", filename)
  5536. self.file_saved.emit("project", filename)
  5537. if not make_copy:
  5538. self.project_filename = filename
  5539. self.should_we_save = False
  5540. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5541. """
  5542. Exports a Geometry Object to an SVG file.
  5543. :param filename: Path to the SVG file to save to.
  5544. :return:
  5545. """
  5546. self.report_usage("export_svg()")
  5547. if filename is None:
  5548. filename = self.defaults["global_last_save_folder"]
  5549. self.log.debug("export_svg()")
  5550. try:
  5551. obj = self.collection.get_by_name(str(obj_name))
  5552. except:
  5553. # TODO: The return behavior has not been established... should raise exception?
  5554. return "Could not retrieve object: %s" % obj_name
  5555. with self.proc_container.new(_("Exporting SVG")) as proc:
  5556. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5557. # Determine bounding area for svg export
  5558. bounds = obj.bounds()
  5559. size = obj.size()
  5560. # Convert everything to strings for use in the xml doc
  5561. svgwidth = str(size[0])
  5562. svgheight = str(size[1])
  5563. minx = str(bounds[0])
  5564. miny = str(bounds[1] - size[1])
  5565. uom = obj.units.lower()
  5566. # Add a SVG Header and footer to the svg output from shapely
  5567. # The transform flips the Y Axis so that everything renders
  5568. # properly within svg apps such as inkscape
  5569. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5570. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5571. svg_header += 'width="' + svgwidth + uom + '" '
  5572. svg_header += 'height="' + svgheight + uom + '" '
  5573. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5574. svg_header += '<g transform="scale(1,-1)">'
  5575. svg_footer = '</g> </svg>'
  5576. svg_elem = svg_header + exported_svg + svg_footer
  5577. # Parse the xml through a xml parser just to add line feeds
  5578. # and to make it look more pretty for the output
  5579. svgcode = parse_xml_string(svg_elem)
  5580. with open(filename, 'w') as fp:
  5581. fp.write(svgcode.toprettyxml())
  5582. if self.defaults["global_open_style"] is False:
  5583. self.file_opened.emit("SVG", filename)
  5584. self.file_saved.emit("SVG", filename)
  5585. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5586. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5587. """
  5588. Exports a Geometry Object to an SVG file in negative.
  5589. :param filename: Path to the SVG file to save to.
  5590. :param: use_thread: If True use threads
  5591. :type: Bool
  5592. :return:
  5593. """
  5594. self.report_usage("export_negative()")
  5595. if filename is None:
  5596. filename = self.defaults["global_last_save_folder"]
  5597. self.log.debug("export_svg() negative")
  5598. try:
  5599. obj = self.collection.get_by_name(str(obj_name))
  5600. except:
  5601. # TODO: The return behavior has not been established... should raise exception?
  5602. return "Could not retrieve object: %s" % obj_name
  5603. try:
  5604. box = self.collection.get_by_name(str(box_name))
  5605. except:
  5606. # TODO: The return behavior has not been established... should raise exception?
  5607. return "Could not retrieve object: %s" % box_name
  5608. if box is None:
  5609. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5610. box = obj
  5611. def make_negative_film():
  5612. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5613. self.progress.emit(40)
  5614. # Determine bounding area for svg export
  5615. bounds = box.bounds()
  5616. size = box.size()
  5617. uom = obj.units.lower()
  5618. # Convert everything to strings for use in the xml doc
  5619. svgwidth = str(size[0] + (2 * boundary))
  5620. svgheight = str(size[1] + (2 * boundary))
  5621. minx = str(bounds[0] - boundary)
  5622. miny = str(bounds[1] + boundary + size[1])
  5623. miny_rect = str(bounds[1] - boundary)
  5624. # Add a SVG Header and footer to the svg output from shapely
  5625. # The transform flips the Y Axis so that everything renders
  5626. # properly within svg apps such as inkscape
  5627. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5628. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5629. svg_header += 'width="' + svgwidth + uom + '" '
  5630. svg_header += 'height="' + svgheight + uom + '" '
  5631. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5632. svg_header += '>'
  5633. svg_header += '<g transform="scale(1,-1)">'
  5634. svg_footer = '</g> </svg>'
  5635. self.progress.emit(60)
  5636. # Change the attributes of the exported SVG
  5637. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5638. # We set opacity to maximum
  5639. # We set the color to WHITE
  5640. root = ET.fromstring(exported_svg)
  5641. for child in root:
  5642. child.set('fill', '#FFFFFF')
  5643. child.set('opacity', '1.0')
  5644. child.set('stroke', '#FFFFFF')
  5645. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5646. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5647. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5648. first_svg_elem_tag = 'rect'
  5649. first_svg_elem_attribs = {
  5650. 'x': minx,
  5651. 'y': miny_rect,
  5652. 'width': svgwidth,
  5653. 'height': svgheight,
  5654. 'id': 'neg_rect',
  5655. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5656. }
  5657. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5658. exported_svg = ET.tostring(root)
  5659. svg_elem = svg_header + str(exported_svg) + svg_footer
  5660. self.progress.emit(80)
  5661. # Parse the xml through a xml parser just to add line feeds
  5662. # and to make it look more pretty for the output
  5663. doc = parse_xml_string(svg_elem)
  5664. with open(filename, 'w') as fp:
  5665. fp.write(doc.toprettyxml())
  5666. self.progress.emit(100)
  5667. if self.defaults["global_open_style"] is False:
  5668. self.file_opened.emit("SVG", filename)
  5669. self.file_saved.emit("SVG", filename)
  5670. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5671. if use_thread is True:
  5672. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5673. def job_thread_film(app_obj):
  5674. try:
  5675. make_negative_film()
  5676. except Exception as e:
  5677. proc.done()
  5678. return
  5679. proc.done()
  5680. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5681. else:
  5682. make_negative_film()
  5683. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5684. """
  5685. Exports a Geometry Object to an SVG file in negative.
  5686. :param filename: Path to the SVG file to save to.
  5687. :param: use_thread: If True use threads
  5688. :type: Bool
  5689. :return:
  5690. """
  5691. self.report_usage("export_svg_black()")
  5692. if filename is None:
  5693. filename = self.defaults["global_last_save_folder"]
  5694. self.log.debug("export_svg() black")
  5695. try:
  5696. obj = self.collection.get_by_name(str(obj_name))
  5697. except:
  5698. # TODO: The return behavior has not been established... should raise exception?
  5699. return "Could not retrieve object: %s" % obj_name
  5700. try:
  5701. box = self.collection.get_by_name(str(box_name))
  5702. except:
  5703. # TODO: The return behavior has not been established... should raise exception?
  5704. return "Could not retrieve object: %s" % box_name
  5705. if box is None:
  5706. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5707. box = obj
  5708. def make_black_film():
  5709. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5710. self.progress.emit(40)
  5711. # Change the attributes of the exported SVG
  5712. # We don't need stroke-width
  5713. # We set opacity to maximum
  5714. # We set the colour to WHITE
  5715. root = ET.fromstring(exported_svg)
  5716. for child in root:
  5717. child.set('fill', '#000000')
  5718. child.set('opacity', '1.0')
  5719. child.set('stroke', '#000000')
  5720. exported_svg = ET.tostring(root)
  5721. # Determine bounding area for svg export
  5722. bounds = box.bounds()
  5723. size = box.size()
  5724. # This contain the measure units
  5725. uom = obj.units.lower()
  5726. # Define a boundary around SVG of about 1.0mm (~39mils)
  5727. if uom in "mm":
  5728. boundary = 1.0
  5729. else:
  5730. boundary = 0.0393701
  5731. self.progress.emit(80)
  5732. # Convert everything to strings for use in the xml doc
  5733. svgwidth = str(size[0] + (2 * boundary))
  5734. svgheight = str(size[1] + (2 * boundary))
  5735. minx = str(bounds[0] - boundary)
  5736. miny = str(bounds[1] + boundary + size[1])
  5737. self.log.debug(minx)
  5738. self.log.debug(miny)
  5739. # Add a SVG Header and footer to the svg output from shapely
  5740. # The transform flips the Y Axis so that everything renders
  5741. # properly within svg apps such as inkscape
  5742. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5743. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5744. svg_header += 'width="' + svgwidth + uom + '" '
  5745. svg_header += 'height="' + svgheight + uom + '" '
  5746. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5747. svg_header += '>'
  5748. svg_header += '<g transform="scale(1,-1)">'
  5749. svg_footer = '</g> </svg>'
  5750. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5751. self.progress.emit(90)
  5752. # Parse the xml through a xml parser just to add line feeds
  5753. # and to make it look more pretty for the output
  5754. doc = parse_xml_string(svg_elem)
  5755. with open(filename, 'w') as fp:
  5756. fp.write(doc.toprettyxml())
  5757. self.progress.emit(100)
  5758. if self.defaults["global_open_style"] is False:
  5759. self.file_opened.emit("SVG", filename)
  5760. self.file_saved.emit("SVG", filename)
  5761. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5762. if use_thread is True:
  5763. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5764. def job_thread_film(app_obj):
  5765. try:
  5766. make_black_film()
  5767. except Exception as e:
  5768. proc.done()
  5769. return
  5770. proc.done()
  5771. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5772. else:
  5773. make_black_film()
  5774. def save_source_file(self, obj_name, filename, use_thread=True):
  5775. """
  5776. Exports a Gerber Object to an Gerber file.
  5777. :param filename: Path to the Gerber file to save to.
  5778. :return:
  5779. """
  5780. self.report_usage("save source file()")
  5781. if filename is None:
  5782. filename = self.defaults["global_last_save_folder"]
  5783. self.log.debug("save source file()")
  5784. obj = self.collection.get_by_name(obj_name)
  5785. file_string = StringIO(obj.source_file)
  5786. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5787. with open(filename, 'w') as file:
  5788. file.writelines('G04*\n')
  5789. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5790. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5791. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5792. file.writelines('G04 Created on : %s*\n' % time_string)
  5793. for line in file_string:
  5794. file.writelines(line)
  5795. def export_excellon(self, obj_name, filename, use_thread=True):
  5796. """
  5797. Exports a Excellon Object to an Excellon file.
  5798. :param filename: Path to the Excellon file to save to.
  5799. :return:
  5800. """
  5801. self.report_usage("export_excellon()")
  5802. if filename is None:
  5803. filename = self.defaults["global_last_save_folder"]
  5804. self.log.debug("export_excellon()")
  5805. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5806. self.defaults["excellon_exp_decimals"]
  5807. )
  5808. units = ''
  5809. try:
  5810. obj = self.collection.get_by_name(str(obj_name))
  5811. except:
  5812. # TODO: The return behavior has not been established... should raise exception?
  5813. return "Could not retrieve object: %s" % obj_name
  5814. # updated units
  5815. eunits = self.defaults["excellon_exp_units"]
  5816. ewhole = self.defaults["excellon_exp_integer"]
  5817. efract = self.defaults["excellon_exp_decimals"]
  5818. ezeros = self.defaults["excellon_exp_zeros"]
  5819. eformat = self.defaults[ "excellon_exp_format"]
  5820. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5821. if fc_units == 'MM':
  5822. factor = 1 if eunits == 'METRIC' else 0.03937
  5823. else:
  5824. factor = 25.4 if eunits == 'METRIC' else 1
  5825. def make_excellon():
  5826. try:
  5827. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5828. header = 'M48\n'
  5829. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5830. (str(self.version), str(self.version_date))
  5831. header += ';Filename: %s' % str(obj_name) + '\n'
  5832. header += ';Created on : %s' % time_str + '\n'
  5833. if eformat == 'dec':
  5834. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5835. header += eunits + '\n'
  5836. for tool in obj.tools:
  5837. if eunits == 'METRIC':
  5838. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5839. tool=str(tool),
  5840. dec=2)
  5841. else:
  5842. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5843. tool=str(tool),
  5844. dec=4)
  5845. else:
  5846. if ezeros == 'LZ':
  5847. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5848. form='ndec', e_zeros='LZ', factor=factor)
  5849. header += '%s,%s\n' % (eunits, 'LZ')
  5850. header += format_exc
  5851. for tool in obj.tools:
  5852. if eunits == 'METRIC':
  5853. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5854. tool=str(tool),
  5855. dec=2)
  5856. else:
  5857. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5858. tool=str(tool),
  5859. dec=4)
  5860. else:
  5861. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5862. form='ndec', e_zeros='TZ', factor=factor)
  5863. header += '%s,%s\n' % (eunits, 'TZ')
  5864. header += format_exc
  5865. for tool in obj.tools:
  5866. if eunits == 'METRIC':
  5867. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5868. tool=str(tool),
  5869. dec=2)
  5870. else:
  5871. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5872. tool=str(tool),
  5873. dec=4)
  5874. header += '%\n'
  5875. footer = 'M30\n'
  5876. exported_excellon = header
  5877. exported_excellon += excellon_code
  5878. exported_excellon += footer
  5879. with open(filename, 'w') as fp:
  5880. fp.write(exported_excellon)
  5881. if self.defaults["global_open_style"] is False:
  5882. self.file_opened.emit("Excellon", filename)
  5883. self.file_saved.emit("Excellon", filename)
  5884. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5885. except Exception as e:
  5886. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5887. return 'fail'
  5888. if use_thread is True:
  5889. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5890. def job_thread_exc(app_obj):
  5891. ret = make_excellon()
  5892. if ret == 'fail':
  5893. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5894. return
  5895. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5896. else:
  5897. ret = make_excellon()
  5898. if ret == 'fail':
  5899. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5900. return
  5901. def export_gerber(self, obj_name, filename, use_thread=True):
  5902. """
  5903. Exports a Gerber Object to an Gerber file.
  5904. :param filename: Path to the Gerber file to save to.
  5905. :return:
  5906. """
  5907. self.report_usage("export_gerber()")
  5908. if filename is None:
  5909. filename = self.defaults["global_last_save_folder"]
  5910. self.log.debug("export_gerber()")
  5911. try:
  5912. obj = self.collection.get_by_name(str(obj_name))
  5913. except:
  5914. # TODO: The return behavior has not been established... should raise exception?
  5915. return "Could not retrieve object: %s" % obj_name
  5916. # updated units
  5917. gunits = self.defaults["gerber_exp_units"]
  5918. gwhole = self.defaults["gerber_exp_integer"]
  5919. gfract = self.defaults["gerber_exp_decimals"]
  5920. gzeros = self.defaults["gerber_exp_zeros"]
  5921. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5922. if fc_units == 'MM':
  5923. factor = 1 if gunits == 'MM' else 0.03937
  5924. else:
  5925. factor = 25.4 if gunits == 'MM' else 1
  5926. def make_gerber():
  5927. try:
  5928. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5929. header = 'G04*\n'
  5930. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  5931. (str(self.version), str(self.version_date))
  5932. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  5933. header += 'G04 Created on : %s*' % time_str + '\n'
  5934. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  5935. header += "%MO{units}*%\n".format(units=gunits)
  5936. for apid in obj.apertures:
  5937. if obj.apertures[apid]['type'] == 'C':
  5938. header += "%ADD{apid}{type},{size}*%\n".format(
  5939. apid=str(apid),
  5940. type='C',
  5941. size=(factor * obj.apertures[apid]['size'])
  5942. )
  5943. elif obj.apertures[apid]['type'] == 'R':
  5944. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5945. apid=str(apid),
  5946. type='R',
  5947. width=(factor * obj.apertures[apid]['width']),
  5948. height=(factor * obj.apertures[apid]['height'])
  5949. )
  5950. elif obj.apertures[apid]['type'] == 'O':
  5951. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5952. apid=str(apid),
  5953. type='O',
  5954. width=(factor * obj.apertures[apid]['width']),
  5955. height=(factor * obj.apertures[apid]['height'])
  5956. )
  5957. header += '\n'
  5958. # obsolete units but some software may need it
  5959. if gunits == 'IN':
  5960. header += 'G70*\n'
  5961. else:
  5962. header += 'G71*\n'
  5963. # Absolute Mode
  5964. header += 'G90*\n'
  5965. header += 'G01*\n'
  5966. # positive polarity
  5967. header += '%LPD*%\n'
  5968. footer = 'M02*\n'
  5969. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  5970. exported_gerber = header
  5971. exported_gerber += gerber_code
  5972. exported_gerber += footer
  5973. with open(filename, 'w') as fp:
  5974. fp.write(exported_gerber)
  5975. if self.defaults["global_open_style"] is False:
  5976. self.file_opened.emit("Gerber", filename)
  5977. self.file_saved.emit("Gerber", filename)
  5978. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  5979. except Exception as e:
  5980. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  5981. return 'fail'
  5982. if use_thread is True:
  5983. with self.proc_container.new(_("Exporting Gerber")) as proc:
  5984. def job_thread_exc(app_obj):
  5985. ret = make_gerber()
  5986. if ret == 'fail':
  5987. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  5988. return
  5989. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5990. else:
  5991. ret = make_gerber()
  5992. if ret == 'fail':
  5993. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  5994. return
  5995. def export_dxf(self, obj_name, filename, use_thread=True):
  5996. """
  5997. Exports a Geometry Object to an DXF file.
  5998. :param filename: Path to the DXF file to save to.
  5999. :return:
  6000. """
  6001. self.report_usage("export_dxf()")
  6002. if filename is None:
  6003. filename = self.defaults["global_last_save_folder"]
  6004. self.log.debug("export_dxf()")
  6005. format_exc = ''
  6006. units = ''
  6007. try:
  6008. obj = self.collection.get_by_name(str(obj_name))
  6009. except:
  6010. # TODO: The return behavior has not been established... should raise exception?
  6011. return "Could not retrieve object: %s" % obj_name
  6012. # updated units
  6013. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6014. if units == 'IN' or units == 'INCH':
  6015. units = 'INCH'
  6016. elif units == 'MM' or units == 'METIRC':
  6017. units ='METRIC'
  6018. def make_dxf():
  6019. try:
  6020. dxf_code = obj.export_dxf()
  6021. dxf_code.saveas(filename)
  6022. if self.defaults["global_open_style"] is False:
  6023. self.file_opened.emit("DXF", filename)
  6024. self.file_saved.emit("DXF", filename)
  6025. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6026. except:
  6027. return 'fail'
  6028. if use_thread is True:
  6029. with self.proc_container.new(_("Exporting DXF")) as proc:
  6030. def job_thread_exc(app_obj):
  6031. ret = make_dxf()
  6032. if ret == 'fail':
  6033. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6034. return
  6035. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6036. else:
  6037. ret = make_dxf()
  6038. if ret == 'fail':
  6039. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6040. return
  6041. def import_svg(self, filename, geo_type='geometry', outname=None):
  6042. """
  6043. Adds a new Geometry Object to the projects and populates
  6044. it with shapes extracted from the SVG file.
  6045. :param filename: Path to the SVG file.
  6046. :param outname:
  6047. :return:
  6048. """
  6049. self.report_usage("import_svg()")
  6050. obj_type = ""
  6051. if geo_type is None or geo_type == "geometry":
  6052. obj_type = "geometry"
  6053. elif geo_type == "gerber":
  6054. obj_type = geo_type
  6055. else:
  6056. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6057. "Only Geometry and Gerber are supported"))
  6058. return
  6059. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6060. def obj_init(geo_obj, app_obj):
  6061. geo_obj.import_svg(filename, obj_type, units=units)
  6062. geo_obj.multigeo = False
  6063. with self.proc_container.new(_("Importing SVG")) as proc:
  6064. # Object name
  6065. name = outname or filename.split('/')[-1].split('\\')[-1]
  6066. self.new_object(obj_type, name, obj_init, autoselected=False)
  6067. self.progress.emit(20)
  6068. # Register recent file
  6069. self.file_opened.emit("svg", filename)
  6070. # GUI feedback
  6071. self.inform.emit(_("[success] Opened: %s") % filename)
  6072. self.progress.emit(100)
  6073. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6074. """
  6075. Adds a new Geometry Object to the projects and populates
  6076. it with shapes extracted from the DXF file.
  6077. :param filename: Path to the DXF file.
  6078. :param outname:
  6079. :type putname: str
  6080. :return:
  6081. """
  6082. self.report_usage("import_dxf()")
  6083. obj_type = ""
  6084. if geo_type is None or geo_type == "geometry":
  6085. obj_type = "geometry"
  6086. elif geo_type == "gerber":
  6087. obj_type = geo_type
  6088. else:
  6089. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6090. "Only Geometry and Gerber are supported"))
  6091. return
  6092. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6093. def obj_init(geo_obj, app_obj):
  6094. geo_obj.import_dxf(filename, obj_type, units=units)
  6095. geo_obj.multigeo = False
  6096. with self.proc_container.new(_("Importing DXF")) as proc:
  6097. # Object name
  6098. name = outname or filename.split('/')[-1].split('\\')[-1]
  6099. self.new_object(obj_type, name, obj_init, autoselected=False)
  6100. self.progress.emit(20)
  6101. # Register recent file
  6102. self.file_opened.emit("dxf", filename)
  6103. # GUI feedback
  6104. self.inform.emit(_("[success] Opened: %s") % filename)
  6105. self.progress.emit(100)
  6106. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6107. """
  6108. Adds a new Geometry Object to the projects and populates
  6109. it with shapes extracted from the SVG file.
  6110. :param filename: Path to the SVG file.
  6111. :param o_type: type of FlatCAM objeect
  6112. :param dpi: dot per inch
  6113. :param mode: black or color
  6114. :param mask: dictate the level of detail
  6115. :param outname: name for the resulting file
  6116. :return:
  6117. """
  6118. self.report_usage("import_image()")
  6119. if o_type is None or o_type == "geometry":
  6120. obj_type = "geometry"
  6121. elif o_type == "gerber":
  6122. obj_type = o_type
  6123. else:
  6124. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6125. "Only Geometry and Gerber are supported"))
  6126. return
  6127. def obj_init(geo_obj, app_obj):
  6128. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6129. geo_obj.multigeo = False
  6130. with self.proc_container.new(_("Importing Image")) as proc:
  6131. # Object name
  6132. name = outname or filename.split('/')[-1].split('\\')[-1]
  6133. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6134. self.new_object(obj_type, name, obj_init)
  6135. self.progress.emit(20)
  6136. # Register recent file
  6137. self.file_opened.emit("image", filename)
  6138. # GUI feedback
  6139. self.inform.emit(_("[success] Opened: %s") % filename)
  6140. self.progress.emit(100)
  6141. def open_gerber(self, filename, outname=None):
  6142. """
  6143. Opens a Gerber file, parses it and creates a new object for
  6144. it in the program. Thread-safe.
  6145. :param outname: Name of the resulting object. None causes the
  6146. name to be that of the file.
  6147. :param filename: Gerber file filename
  6148. :type filename: str
  6149. :param follow: If true, the parser will not create polygons, just lines
  6150. following the gerber path.
  6151. :type follow: bool
  6152. :return: None
  6153. """
  6154. # How the object should be initialized
  6155. def obj_init(gerber_obj, app_obj):
  6156. assert isinstance(gerber_obj, FlatCAMGerber), \
  6157. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6158. # Opening the file happens here
  6159. self.progress.emit(30)
  6160. try:
  6161. gerber_obj.parse_file(filename)
  6162. except IOError:
  6163. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6164. app_obj.progress.emit(0)
  6165. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6166. return "fail"
  6167. except ParseError as err:
  6168. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6169. error=str(err)))
  6170. app_obj.progress.emit(0)
  6171. self.log.error(str(err))
  6172. return "fail"
  6173. except:
  6174. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  6175. msg += traceback.format_exc()
  6176. app_obj.inform.emit(msg)
  6177. return "fail"
  6178. if gerber_obj.is_empty():
  6179. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6180. # self.collection.set_active(gerber_obj.options["name"])
  6181. # self.collection.delete_active()
  6182. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6183. return "fail"
  6184. # Further parsing
  6185. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6186. App.log.debug("open_gerber()")
  6187. with self.proc_container.new(_("Opening Gerber")) as proc:
  6188. self.progress.emit(10)
  6189. # Object name
  6190. name = outname or filename.split('/')[-1].split('\\')[-1]
  6191. # # ## Object creation # ##
  6192. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6193. if ret == 'fail':
  6194. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6195. return
  6196. # Register recent file
  6197. self.file_opened.emit("gerber", filename)
  6198. self.progress.emit(100)
  6199. # GUI feedback
  6200. self.inform.emit(_("[success] Opened: %s") % filename)
  6201. def open_excellon(self, filename, outname=None):
  6202. """
  6203. Opens an Excellon file, parses it and creates a new object for
  6204. it in the program. Thread-safe.
  6205. :param outname: Name of the resulting object. None causes the
  6206. name to be that of the file.
  6207. :param filename: Excellon file filename
  6208. :type filename: str
  6209. :return: None
  6210. """
  6211. App.log.debug("open_excellon()")
  6212. # How the object should be initialized
  6213. def obj_init(excellon_obj, app_obj):
  6214. # self.progress.emit(20)
  6215. try:
  6216. ret = excellon_obj.parse_file(filename=filename)
  6217. if ret == "fail":
  6218. log.debug("Excellon parsing failed.")
  6219. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6220. return "fail"
  6221. except IOError:
  6222. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6223. log.debug("Could not open Excellon object.")
  6224. self.progress.emit(0) # TODO: self and app_bjj mixed
  6225. return "fail"
  6226. except:
  6227. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6228. msg += traceback.format_exc()
  6229. app_obj.inform.emit(msg)
  6230. return "fail"
  6231. ret = excellon_obj.create_geometry()
  6232. if ret == 'fail':
  6233. log.debug("Could not create geometry for Excellon object.")
  6234. return "fail"
  6235. for tool in excellon_obj.tools:
  6236. if excellon_obj.tools[tool]['solid_geometry']:
  6237. return
  6238. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6239. return "fail"
  6240. with self.proc_container.new(_("Opening Excellon.")):
  6241. # Object name
  6242. name = outname or filename.split('/')[-1].split('\\')[-1]
  6243. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6244. if ret_val == 'fail':
  6245. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6246. return
  6247. # Register recent file
  6248. self.file_opened.emit("excellon", filename)
  6249. # GUI feedback
  6250. self.inform.emit(_("[success] Opened: %s") % filename)
  6251. def open_gcode(self, filename, outname=None):
  6252. """
  6253. Opens a G-gcode file, parses it and creates a new object for
  6254. it in the program. Thread-safe.
  6255. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6256. :param filename: G-code file filename
  6257. :type filename: str
  6258. :return: None
  6259. """
  6260. App.log.debug("open_gcode()")
  6261. # How the object should be initialized
  6262. def obj_init(job_obj, app_obj_):
  6263. """
  6264. :param job_obj: the resulting object
  6265. :type app_obj_: App
  6266. """
  6267. assert isinstance(app_obj_, App), \
  6268. "Initializer expected App, got %s" % type(app_obj_)
  6269. self.progress.emit(10)
  6270. try:
  6271. f = open(filename)
  6272. gcode = f.read()
  6273. f.close()
  6274. except IOError:
  6275. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6276. self.progress.emit(0)
  6277. return "fail"
  6278. job_obj.gcode = gcode
  6279. self.progress.emit(20)
  6280. ret = job_obj.gcode_parse()
  6281. if ret == "fail":
  6282. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6283. return "fail"
  6284. self.progress.emit(60)
  6285. job_obj.create_geometry()
  6286. with self.proc_container.new(_("Opening G-Code.")):
  6287. # Object name
  6288. name = outname or filename.split('/')[-1].split('\\')[-1]
  6289. # New object creation and file processing
  6290. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6291. if ret == 'fail':
  6292. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6293. "Attempting to create a FlatCAM CNCJob Object from "
  6294. "G-Code file failed during processing"))
  6295. return "fail"
  6296. # Register recent file
  6297. self.file_opened.emit("cncjob", filename)
  6298. # GUI feedback
  6299. self.inform.emit(_("[success] Opened: %s") % filename)
  6300. self.progress.emit(100)
  6301. def open_config_file(self, filename, run_from_arg=None):
  6302. """
  6303. Loads a config file from the specified file.
  6304. :param filename: Name of the file from which to load.
  6305. :type filename: str
  6306. :return: None
  6307. """
  6308. App.log.debug("Opening config file: " + filename)
  6309. # add the tab if it was closed
  6310. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6311. # first clear previous text in text editor (if any)
  6312. self.ui.code_editor.clear()
  6313. # Switch plot_area to CNCJob tab
  6314. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6315. try:
  6316. if filename:
  6317. f = QtCore.QFile(filename)
  6318. if f.open(QtCore.QIODevice.ReadOnly):
  6319. stream = QtCore.QTextStream(f)
  6320. gcode_edited = stream.readAll()
  6321. self.ui.code_editor.setPlainText(gcode_edited)
  6322. f.close()
  6323. except IOError:
  6324. App.log.error("Failed to open config file: %s" % filename)
  6325. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6326. return
  6327. def open_project(self, filename, run_from_arg=None):
  6328. """
  6329. Loads a project from the specified file.
  6330. 1) Loads and parses file
  6331. 2) Registers the file as recently opened.
  6332. 3) Calls on_file_new()
  6333. 4) Updates options
  6334. 5) Calls new_object() with the object's from_dict() as init method.
  6335. 6) Calls plot_all()
  6336. :param filename: Name of the file from which to load.
  6337. :type filename: str
  6338. :param run_from_arg: True if run for arguments
  6339. :return: None
  6340. """
  6341. App.log.debug("Opening project: " + filename)
  6342. # Open and parse an uncompressed Project file
  6343. try:
  6344. f = open(filename, 'r')
  6345. except IOError:
  6346. App.log.error("Failed to open project file: %s" % filename)
  6347. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6348. return
  6349. try:
  6350. d = json.load(f, object_hook=dict2obj)
  6351. except Exception as e:
  6352. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  6353. (filename, str(e)))
  6354. f.close()
  6355. # Open and parse a compressed Project file
  6356. try:
  6357. with lzma.open(filename) as f:
  6358. file_content = f.read().decode('utf-8')
  6359. d = json.loads(file_content, object_hook=dict2obj)
  6360. except IOError:
  6361. App.log.error("Failed to open project file: %s" % filename)
  6362. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6363. return
  6364. # Clear the current project
  6365. # # NOT THREAD SAFE # ##
  6366. if run_from_arg is True:
  6367. pass
  6368. else:
  6369. self.on_file_new()
  6370. # Project options
  6371. self.options.update(d['options'])
  6372. self.project_filename = filename
  6373. self.set_screen_units(self.options["units"])
  6374. # Re create objects
  6375. App.log.debug("Re-creating objects...")
  6376. for obj in d['objs']:
  6377. def obj_init(obj_inst, app_inst):
  6378. obj_inst.from_dict(obj)
  6379. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  6380. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6381. self.plot_all()
  6382. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6383. self.should_we_save = False
  6384. self.file_opened.emit("project", filename)
  6385. App.log.debug("Project loaded")
  6386. def propagate_defaults(self, silent=False):
  6387. """
  6388. This method is used to set default values in classes. It's
  6389. an alternative to project options but allows the use
  6390. of values invisible to the user.
  6391. :return: None
  6392. """
  6393. if silent is False:
  6394. self.log.debug("propagate_defaults()")
  6395. # Which objects to update the given parameters.
  6396. routes = {
  6397. "global_zdownrate": CNCjob,
  6398. "excellon_zeros": Excellon,
  6399. "excellon_format_upper_in": Excellon,
  6400. "excellon_format_lower_in": Excellon,
  6401. "excellon_format_upper_mm": Excellon,
  6402. "excellon_format_lower_mm": Excellon,
  6403. "excellon_units": Excellon,
  6404. "gerber_use_buffer_for_union": Gerber,
  6405. "geometry_multidepth": Geometry
  6406. }
  6407. for param in routes:
  6408. if param in routes[param].defaults:
  6409. try:
  6410. routes[param].defaults[param] = self.defaults[param]
  6411. if silent is False:
  6412. self.log.debug(" " + param + " OK")
  6413. except KeyError:
  6414. if silent is False:
  6415. self.log.debug(" ERROR: " + param + " not in defaults.")
  6416. else:
  6417. # Try extracting the name:
  6418. # classname_param here is param in the object
  6419. if param.find(routes[param].__name__.lower() + "_") == 0:
  6420. p = param[len(routes[param].__name__) + 1:]
  6421. if p in routes[param].defaults:
  6422. routes[param].defaults[p] = self.defaults[param]
  6423. if silent is False:
  6424. self.log.debug(" " + param + " OK!")
  6425. def restore_main_win_geom(self):
  6426. try:
  6427. self.ui.setGeometry(self.defaults["global_def_win_x"],
  6428. self.defaults["global_def_win_y"],
  6429. self.defaults["global_def_win_w"],
  6430. self.defaults["global_def_win_h"])
  6431. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  6432. settings = QSettings("Open Source", "FlatCAM")
  6433. if settings.contains("maximized_gui"):
  6434. maximized_ui = settings.value('maximized_gui', type=bool)
  6435. if maximized_ui is True:
  6436. self.ui.showMaximized()
  6437. except KeyError as e:
  6438. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  6439. def plot_all(self, zoom=True):
  6440. """
  6441. Re-generates all plots from all objects.
  6442. :return: None
  6443. """
  6444. self.log.debug("Plot_all()")
  6445. for obj in self.collection.get_list():
  6446. def worker_task(obj):
  6447. with self.proc_container.new("Plotting"):
  6448. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  6449. if zoom:
  6450. self.object_plotted.emit(obj)
  6451. # Send to worker
  6452. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  6453. def register_folder(self, filename):
  6454. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6455. def register_save_folder(self, filename):
  6456. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6457. def set_progress_bar(self, percentage, text=""):
  6458. self.ui.progress_bar.setValue(int(percentage))
  6459. def setup_shell(self):
  6460. """
  6461. Creates shell functions. Runs once at startup.
  6462. :return: None
  6463. """
  6464. self.log.debug("setup_shell()")
  6465. def shelp(p=None):
  6466. if not p:
  6467. return _("Available commands:\n") + \
  6468. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6469. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6470. if p not in commands:
  6471. return "Unknown command: %s" % p
  6472. return commands[p]["help"]
  6473. # --- Migrated to new architecture ---
  6474. # def options(name):
  6475. # ops = self.collection.get_by_name(str(name)).options
  6476. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6477. def h(*args):
  6478. """
  6479. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6480. and standalone parameters into list.
  6481. """
  6482. kwa = {}
  6483. a = []
  6484. n = len(args)
  6485. name = None
  6486. for i in range(n):
  6487. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6488. if match:
  6489. assert name is None
  6490. name = match.group(1)
  6491. continue
  6492. if name is None:
  6493. a.append(args[i])
  6494. else:
  6495. kwa[name] = args[i]
  6496. name = None
  6497. return a, kwa
  6498. @contextmanager
  6499. def wait_signal(signal, timeout=10000):
  6500. """
  6501. Block loop until signal emitted, timeout (ms) elapses
  6502. or unhandled exception happens in a thread.
  6503. :param timeout: time after which the loop is exited
  6504. :param signal: Signal to wait for.
  6505. """
  6506. loop = QtCore.QEventLoop()
  6507. # Normal termination
  6508. signal.connect(loop.quit)
  6509. # Termination by exception in thread
  6510. self.thread_exception.connect(loop.quit)
  6511. status = {'timed_out': False}
  6512. def report_quit():
  6513. status['timed_out'] = True
  6514. loop.quit()
  6515. yield
  6516. # Temporarily change how exceptions are managed.
  6517. oeh = sys.excepthook
  6518. ex = []
  6519. def except_hook(type_, value, traceback_):
  6520. ex.append(value)
  6521. oeh(type_, value, traceback_)
  6522. sys.excepthook = except_hook
  6523. # Terminate on timeout
  6524. if timeout is not None:
  6525. QtCore.QTimer.singleShot(timeout, report_quit)
  6526. # # ## Block ## ##
  6527. loop.exec_()
  6528. # Restore exception management
  6529. sys.excepthook = oeh
  6530. if ex:
  6531. self.raiseTclError(str(ex[0]))
  6532. if status['timed_out']:
  6533. raise Exception('Timed out!')
  6534. def make_docs():
  6535. output = ''
  6536. import collections
  6537. od = collections.OrderedDict(sorted(commands.items()))
  6538. for cmd_, val in od.items():
  6539. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6540. t = val['help']
  6541. usage_i = t.find('>')
  6542. if usage_i < 0:
  6543. expl = t
  6544. output += expl + '\n\n'
  6545. continue
  6546. expl = t[:usage_i - 1]
  6547. output += expl + '\n\n'
  6548. end_usage_i = t[usage_i:].find('\n')
  6549. if end_usage_i < 0:
  6550. end_usage_i = len(t[usage_i:])
  6551. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6552. else:
  6553. extras = t[usage_i+end_usage_i+1:]
  6554. parts = [s.strip() for s in extras.split('\n')]
  6555. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6556. for p in parts:
  6557. output += ' ' + p + '\n\n'
  6558. return output
  6559. '''
  6560. Howto implement TCL shell commands:
  6561. All parameters passed to command should be possible to set as None and test it afterwards.
  6562. This is because we need to see error caused in tcl,
  6563. if None value as default parameter is not allowed TCL will return empty error.
  6564. Use:
  6565. def mycommand(name=None,...):
  6566. Test it like this:
  6567. if name is None:
  6568. self.raise_tcl_error('Argument name is missing.')
  6569. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6570. otherwise we will miss it and processing will silently continue.
  6571. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6572. which is catched in exec_command and displayed in TCL shell console with red background.
  6573. Error in console is displayed with TCL trace.
  6574. This behavior works only within main thread,
  6575. errors with promissed tasks can be catched and detected only with log.
  6576. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  6577. TCL shell.
  6578. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6579. '''
  6580. commands = {
  6581. 'help': {
  6582. 'fcn': shelp,
  6583. 'help': _("Shows list of commands.")
  6584. },
  6585. }
  6586. # Import/overwrite tcl commands as objects of TclCommand descendants
  6587. # This modifies the variable 'commands'.
  6588. tclCommands.register_all_commands(self, commands)
  6589. # Add commands to the tcl interpreter
  6590. for cmd in commands:
  6591. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6592. # Make the tcl puts function return instead of print to stdout
  6593. self.tcl.eval('''
  6594. rename puts original_puts
  6595. proc puts {args} {
  6596. if {[llength $args] == 1} {
  6597. return "[lindex $args 0]"
  6598. } else {
  6599. eval original_puts $args
  6600. }
  6601. }
  6602. ''')
  6603. def setup_recent_items(self):
  6604. # TODO: Move this to constructor
  6605. icons = {
  6606. "gerber": "share/flatcam_icon16.png",
  6607. "excellon": "share/drill16.png",
  6608. 'geometry': "share/geometry16.png",
  6609. "cncjob": "share/cnc16.png",
  6610. "project": "share/project16.png",
  6611. "svg": "share/geometry16.png",
  6612. "dxf": "share/dxf16.png",
  6613. "pdf": "share/pdf32.png",
  6614. "image": "share/image16.png"
  6615. }
  6616. openers = {
  6617. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6618. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6619. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  6620. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6621. 'project': self.open_project,
  6622. 'svg': self.import_svg,
  6623. 'dxf': self.import_dxf,
  6624. 'image': self.import_image,
  6625. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6626. }
  6627. # Open file
  6628. try:
  6629. f = open(self.data_path + '/recent.json')
  6630. except IOError:
  6631. App.log.error("Failed to load recent item list.")
  6632. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6633. return
  6634. try:
  6635. self.recent = json.load(f)
  6636. except json.scanner.JSONDecodeError:
  6637. App.log.error("Failed to parse recent item list.")
  6638. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6639. f.close()
  6640. return
  6641. f.close()
  6642. # Closure needed to create callbacks in a loop.
  6643. # Otherwise late binding occurs.
  6644. def make_callback(func, fname):
  6645. def opener():
  6646. func(fname)
  6647. return opener
  6648. def reset_recent():
  6649. # Reset menu
  6650. self.ui.recent.clear()
  6651. self.recent = []
  6652. try:
  6653. f = open(self.data_path + '/recent.json', 'w')
  6654. except IOError:
  6655. App.log.error("Failed to open recent items file for writing.")
  6656. return
  6657. json.dump(self.recent, f)
  6658. # Reset menu
  6659. self.ui.recent.clear()
  6660. # Create menu items
  6661. for recent in self.recent:
  6662. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6663. try:
  6664. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6665. # Attach callback
  6666. o = make_callback(openers[recent["kind"]], recent['filename'])
  6667. action.triggered.connect(o)
  6668. self.ui.recent.addAction(action)
  6669. except KeyError:
  6670. App.log.error("Unsupported file type: %s" % recent["kind"])
  6671. # Last action in Recent Files menu is one that Clear the content
  6672. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6673. clear_action.triggered.connect(reset_recent)
  6674. self.ui.recent.addSeparator()
  6675. self.ui.recent.addAction(clear_action)
  6676. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6677. # self.ui.menufilerecent.set_submenu(recent_menu)
  6678. # recent_menu.show_all()
  6679. # self.ui.recent.show()
  6680. self.log.debug("Recent items list has been populated.")
  6681. def setup_component_editor(self):
  6682. # label = QtWidgets.QLabel("Choose an item from Project")
  6683. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6684. sel_title = QtWidgets.QTextEdit(
  6685. _('<b>Shortcut Key List</b>'))
  6686. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6687. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6688. # font = self.sel_title.font()
  6689. # font.setPointSize(12)
  6690. # self.sel_title.setFont(font)
  6691. selected_text = _('''
  6692. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6693. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6694. The normal flow when working in FlatCAM is the following:</span></p>
  6695. <ol>
  6696. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  6697. <br />
  6698. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  6699. &nbsp;</li>
  6700. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  6701. <br />
  6702. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  6703. <br />
  6704. You can change the parameters in this screen and the flow direction is like this:<br />
  6705. <br />
  6706. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  6707. </ol>
  6708. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  6709. ''')
  6710. sel_title.setText(selected_text)
  6711. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6712. self.ui.selected_scroll_area.setWidget(sel_title)
  6713. # tool_title = QtWidgets.QTextEdit(
  6714. # '<b>Shortcut Key List</b>')
  6715. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6716. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6717. # # font = self.sel_title.font()
  6718. # # font.setPointSize(12)
  6719. # # self.sel_title.setFont(font)
  6720. #
  6721. # tool_text = '''
  6722. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6723. #
  6724. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6725. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6726. #
  6727. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6728. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6729. #
  6730. # <ol>
  6731. # </ol>
  6732. #
  6733. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  6734. #
  6735. # '''
  6736. #
  6737. # tool_title.setText(tool_text)
  6738. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6739. #
  6740. # self.ui.tool_scroll_area.setWidget(tool_title)
  6741. def setup_obj_classes(self):
  6742. """
  6743. Sets up application specifics on the FlatCAMObj class.
  6744. :return: None
  6745. """
  6746. FlatCAMObj.app = self
  6747. ObjectCollection.app = self
  6748. FCProcess.app = self
  6749. FCProcessContainer.app = self
  6750. def version_check(self):
  6751. """
  6752. Checks for the latest version of the program. Alerts the
  6753. user if theirs is outdated. This method is meant to be run
  6754. in a separate thread.
  6755. :return: None
  6756. """
  6757. self.log.debug("version_check()")
  6758. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6759. full_url = App.version_url + \
  6760. "?s=" + str(self.defaults['global_serial']) + \
  6761. "&v=" + str(self.version) + \
  6762. "&os=" + str(self.os) + \
  6763. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6764. else:
  6765. # no_stats dict; just so it won't break things on website
  6766. no_ststs_dict = {}
  6767. no_ststs_dict["global_ststs"] = {}
  6768. full_url = App.version_url + \
  6769. "?s=" + str(self.defaults['global_serial']) + \
  6770. "&v=" + str(self.version) + \
  6771. "&os=" + str(self.os) + \
  6772. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6773. App.log.debug("Checking for updates @ %s" % full_url)
  6774. # ## Get the data
  6775. try:
  6776. f = urllib.request.urlopen(full_url)
  6777. except:
  6778. # App.log.warning("Failed checking for latest version. Could not connect.")
  6779. self.log.warning("Failed checking for latest version. Could not connect.")
  6780. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6781. return
  6782. try:
  6783. data = json.load(f)
  6784. except Exception as e:
  6785. App.log.error("Could not parse information about latest version.")
  6786. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6787. App.log.debug("json.load(): %s" % str(e))
  6788. f.close()
  6789. return
  6790. f.close()
  6791. # ## Latest version?
  6792. if self.version >= data["version"]:
  6793. App.log.debug("FlatCAM is up to date!")
  6794. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6795. return
  6796. App.log.debug("Newer version available.")
  6797. self.message.emit(
  6798. _("Newer Version Available"),
  6799. _("There is a newer version of FlatCAM available for download:\n\n") +
  6800. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6801. _("info")
  6802. )
  6803. def on_zoom_fit(self, event):
  6804. """
  6805. Callback for zoom-out request. This can be either from the corresponding
  6806. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6807. with axes limits from the geometry bounds of all objects.
  6808. :param event: Ignored.
  6809. :return: None
  6810. """
  6811. self.plotcanvas.fit_view()
  6812. def disable_all_plots(self):
  6813. self.report_usage("disable_all_plots()")
  6814. self.disable_plots(self.collection.get_list())
  6815. self.inform.emit(_("[success] All plots disabled."))
  6816. def disable_other_plots(self):
  6817. self.report_usage("disable_other_plots()")
  6818. self.disable_plots(self.collection.get_non_selected())
  6819. self.inform.emit(_("[success] All non selected plots disabled."))
  6820. def enable_all_plots(self):
  6821. self.report_usage("enable_all_plots()")
  6822. self.enable_plots(self.collection.get_list())
  6823. self.inform.emit(_("[success] All plots enabled."))
  6824. # TODO: FIX THIS
  6825. '''
  6826. By default this is not threaded
  6827. If threaded the app give warnings like this:
  6828. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6829. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6830. '''
  6831. def enable_plots(self, objects, threaded=True):
  6832. if threaded is True:
  6833. def worker_task(app_obj):
  6834. # percentage = 0.1
  6835. # try:
  6836. # delta = 0.9 / len(objects)
  6837. # except ZeroDivisionError:
  6838. # self.progress.emit(0)
  6839. # return
  6840. for obj in objects:
  6841. obj.options['plot'] = True
  6842. # percentage += delta
  6843. # self.progress.emit(int(percentage*100))
  6844. # self.progress.emit(0)
  6845. self.plots_updated.emit()
  6846. # self.collection.update_view()
  6847. # Send to worker
  6848. # self.worker.add_task(worker_task, [self])
  6849. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6850. else:
  6851. for obj in objects:
  6852. obj.options['plot'] = True
  6853. # self.progress.emit(0)
  6854. self.plots_updated.emit()
  6855. # self.collection.update_view()
  6856. # TODO: FIX THIS
  6857. '''
  6858. By default this is not threaded
  6859. If threaded the app give warnings like this:
  6860. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6861. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6862. '''
  6863. def disable_plots(self, objects, threaded=True):
  6864. # TODO: This method is very similar to replot_all. Try to merge.
  6865. """
  6866. Disables plots
  6867. :param objects: list
  6868. Objects to be disabled
  6869. :return:
  6870. """
  6871. if threaded is True:
  6872. # self.progress.emit(10)
  6873. def worker_task(app_obj):
  6874. # percentage = 0.1
  6875. # try:
  6876. # delta = 0.9 / len(objects)
  6877. # except ZeroDivisionError:
  6878. # self.progress.emit(0)
  6879. # return
  6880. for obj in objects:
  6881. obj.options['plot'] = False
  6882. # percentage += delta
  6883. # self.progress.emit(int(percentage*100))
  6884. # self.progress.emit(0)
  6885. self.plots_updated.emit()
  6886. # self.collection.update_view()
  6887. # Send to worker
  6888. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6889. else:
  6890. for obj in objects:
  6891. obj.options['plot'] = False
  6892. self.plots_updated.emit()
  6893. # self.collection.update_view()
  6894. def clear_plots(self):
  6895. objects = self.collection.get_list()
  6896. for obj in objects:
  6897. obj.clear(obj == objects[-1])
  6898. # Clear pool to free memory
  6899. self.clear_pool()
  6900. def generate_cnc_job(self, objects):
  6901. self.report_usage("generate_cnc_job()")
  6902. # for obj in objects:
  6903. # obj.generatecncjob()
  6904. for obj in objects:
  6905. obj.on_generatecnc_button_click()
  6906. def save_project(self, filename, quit=False):
  6907. """
  6908. Saves the current project to the specified file.
  6909. :param filename: Name of the file in which to save.
  6910. :type filename: str
  6911. :return: None
  6912. """
  6913. self.log.debug("save_project()")
  6914. self.save_in_progress = True
  6915. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6916. # Capture the latest changes
  6917. # Current object
  6918. try:
  6919. self.collection.get_active().read_form()
  6920. except:
  6921. self.log.debug("There was no active object")
  6922. pass
  6923. # Project options
  6924. self.options_read_form()
  6925. # Serialize the whole project
  6926. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6927. "options": self.options,
  6928. "version": self.version}
  6929. if self.defaults["global_save_compressed"] is True:
  6930. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6931. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6932. # # Write
  6933. f.write(g)
  6934. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6935. else:
  6936. # Open file
  6937. try:
  6938. f = open(filename, 'w')
  6939. except IOError:
  6940. App.log.error("Failed to open file for saving: %s", filename)
  6941. return
  6942. # Write
  6943. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6944. f.close()
  6945. # verification of the saved project
  6946. # Open and parse
  6947. try:
  6948. saved_f = open(filename, 'r')
  6949. except IOError:
  6950. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6951. return
  6952. try:
  6953. saved_d = json.load(saved_f, object_hook=dict2obj)
  6954. except:
  6955. self.inform.emit(
  6956. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6957. f.close()
  6958. return
  6959. saved_f.close()
  6960. if 'version' in saved_d:
  6961. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6962. else:
  6963. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6964. # if quit:
  6965. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6966. # t.start()
  6967. self.start_delayed_quit(delay=500, filename=filename, quit=quit)
  6968. def start_delayed_quit(self, delay, filename, quit=None):
  6969. """
  6970. :param delay: period of checking if project file size is more than zero; in seconds
  6971. :param filename: the name of the project file to be checked periodically for size more than zero
  6972. :return:
  6973. """
  6974. to_quit = quit
  6975. self.save_timer = QtCore.QTimer()
  6976. self.save_timer.setInterval(delay)
  6977. self.save_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename, quit=to_quit))
  6978. self.save_timer.start()
  6979. def check_project_file_size(self, filename, quit=None):
  6980. """
  6981. :param filename: the name of the project file to be checked periodically for size more than zero
  6982. :return:
  6983. """
  6984. try:
  6985. if os.stat(filename).st_size > 0:
  6986. self.save_in_progress = False
  6987. self.save_timer.stop()
  6988. if quit:
  6989. self.app_quit.emit()
  6990. except Exception:
  6991. traceback.print_exc()
  6992. def on_options_app2project(self):
  6993. """
  6994. Callback for Options->Transfer Options->App=>Project. Copies options
  6995. from application defaults to project defaults.
  6996. :return: None
  6997. """
  6998. self.report_usage("on_options_app2project")
  6999. self.defaults_read_form()
  7000. self.options.update(self.defaults)
  7001. self.options_write_form()
  7002. def on_options_project2app(self):
  7003. """
  7004. Callback for Options->Transfer Options->Project=>App. Copies options
  7005. from project defaults to application defaults.
  7006. :return: None
  7007. """
  7008. self.report_usage("on_options_project2app")
  7009. self.options_read_form()
  7010. self.defaults.update(self.options)
  7011. self.defaults_write_form()
  7012. def on_options_project2object(self):
  7013. """
  7014. Callback for Options->Transfer Options->Project=>Object. Copies options
  7015. from project defaults to the currently selected object.
  7016. :return: None
  7017. """
  7018. self.report_usage("on_options_project2object")
  7019. self.options_read_form()
  7020. obj = self.collection.get_active()
  7021. if obj is None:
  7022. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7023. return
  7024. for option in self.options:
  7025. if option.find(obj.kind + "_") == 0:
  7026. oname = option[len(obj.kind) + 1:]
  7027. obj.options[oname] = self.options[option]
  7028. obj.to_form() # Update UI
  7029. def on_options_object2project(self):
  7030. """
  7031. Callback for Options->Transfer Options->Object=>Project. Copies options
  7032. from the currently selected object to project defaults.
  7033. :return: None
  7034. """
  7035. self.report_usage("on_options_object2project")
  7036. obj = self.collection.get_active()
  7037. if obj is None:
  7038. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7039. return
  7040. obj.read_form()
  7041. for option in obj.options:
  7042. if option in ['name']: # TODO: Handle this better...
  7043. continue
  7044. self.options[obj.kind + "_" + option] = obj.options[option]
  7045. self.options_write_form()
  7046. def on_options_object2app(self):
  7047. """
  7048. Callback for Options->Transfer Options->Object=>App. Copies options
  7049. from the currently selected object to application defaults.
  7050. :return: None
  7051. """
  7052. self.report_usage("on_options_object2app")
  7053. obj = self.collection.get_active()
  7054. if obj is None:
  7055. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7056. return
  7057. obj.read_form()
  7058. for option in obj.options:
  7059. if option in ['name']: # TODO: Handle this better...
  7060. continue
  7061. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7062. self.defaults_write_form()
  7063. def on_options_app2object(self):
  7064. """
  7065. Callback for Options->Transfer Options->App=>Object. Copies options
  7066. from application defaults to the currently selected object.
  7067. :return: None
  7068. """
  7069. self.report_usage("on_options_app2object")
  7070. self.defaults_read_form()
  7071. obj = self.collection.get_active()
  7072. if obj is None:
  7073. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7074. return
  7075. for option in self.defaults:
  7076. if option.find(obj.kind + "_") == 0:
  7077. oname = option[len(obj.kind) + 1:]
  7078. obj.options[oname] = self.defaults[option]
  7079. obj.to_form() # Update UI
  7080. # end of file