FlatCAMApp.py 480 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755
  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
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import winreg
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool
  28. import socket
  29. from array import array
  30. # #######################################
  31. # # Imports part of FlatCAM ##
  32. # #######################################
  33. from ObjectCollection import *
  34. from FlatCAMObj import *
  35. from flatcamGUI.PlotCanvas import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. if '_' not in builtins.__dict__:
  54. _ = gettext.gettext
  55. # ########################################
  56. # # App ###
  57. # ########################################
  58. class App(QtCore.QObject):
  59. """
  60. The main application class. The constructor starts the GUI.
  61. """
  62. # Get Cmd Line Options
  63. cmd_line_shellfile = ''
  64. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  65. try:
  66. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  67. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  68. except getopt.GetoptError:
  69. print(cmd_line_help)
  70. sys.exit(2)
  71. for opt, arg in cmd_line_options:
  72. if opt == '-h':
  73. print(cmd_line_help)
  74. sys.exit()
  75. elif opt == '--shellfile':
  76. cmd_line_shellfile = arg
  77. # ## Logging ###
  78. log = logging.getLogger('base')
  79. log.setLevel(logging.DEBUG)
  80. # log.setLevel(logging.WARNING)
  81. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  82. handler = logging.StreamHandler()
  83. handler.setFormatter(formatter)
  84. log.addHandler(handler)
  85. # ##########################################################################
  86. # ################## Version and VERSION DATE ##############################
  87. # ##########################################################################
  88. version = 8.97
  89. version_date = "2019/09/15"
  90. beta = True
  91. # current date now
  92. date = str(datetime.today()).rpartition('.')[0]
  93. date = ''.join(c for c in date if c not in ':-')
  94. date = date.replace(' ', '_')
  95. # URL for update checks and statistics
  96. version_url = "http://flatcam.org/version"
  97. # App URL
  98. app_url = "http://flatcam.org"
  99. # Manual URL
  100. manual_url = "http://flatcam.org/manual/index.html"
  101. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  102. # this variable will hold the project status
  103. # if True it will mean that the project was modified and not saved
  104. should_we_save = False
  105. # flag is True if saving action has been triggered
  106. save_in_progress = False
  107. # ###########################################################################
  108. # ############################# Signals ################################
  109. # ###########################################################################
  110. # Inform the user
  111. # Handled by:
  112. # * App.info() --> Print on the status bar
  113. inform = QtCore.pyqtSignal(str)
  114. app_quit = QtCore.pyqtSignal()
  115. # General purpose background task
  116. worker_task = QtCore.pyqtSignal(dict)
  117. # File opened
  118. # Handled by:
  119. # * register_folder()
  120. # * register_recent()
  121. # Note: Setting the parameters to unicode does not seem
  122. # to have an effect. Then are received as Qstring
  123. # anyway.
  124. # File type and filename
  125. file_opened = QtCore.pyqtSignal(str, str)
  126. # File type and filename
  127. file_saved = QtCore.pyqtSignal(str, str)
  128. # Percentage of progress
  129. progress = QtCore.pyqtSignal(int)
  130. plots_updated = QtCore.pyqtSignal()
  131. # Emitted by new_object() and passes the new object as argument, plot flag.
  132. # on_object_created() adds the object to the collection, plots on appropriate flag
  133. # and emits new_object_available.
  134. object_created = QtCore.pyqtSignal(object, bool, bool)
  135. # Emitted when a object has been changed (like scaled, mirrored)
  136. object_changed = QtCore.pyqtSignal(object)
  137. # Emitted after object has been plotted.
  138. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  139. object_plotted = QtCore.pyqtSignal(object)
  140. # Emitted when a new object has been added or deleted from/to the collection
  141. object_status_changed = QtCore.pyqtSignal(object, str)
  142. message = QtCore.pyqtSignal(str, str, str)
  143. # Emmited when shell command is finished(one command only)
  144. shell_command_finished = QtCore.pyqtSignal(object)
  145. # Emitted when multiprocess pool has been recreated
  146. pool_recreated = QtCore.pyqtSignal(object)
  147. # Emitted when an unhandled exception happens
  148. # in the worker task.
  149. thread_exception = QtCore.pyqtSignal(object)
  150. # used to signal that there are arguments for the app
  151. args_at_startup = QtCore.pyqtSignal(list)
  152. # a reusable signal to replot a list of objects
  153. # should be disconnected after use so it can be reused
  154. replot_signal = pyqtSignal(list)
  155. def __init__(self, user_defaults=True, post_gui=None):
  156. """
  157. Starts the application.
  158. :return: app
  159. :rtype: App
  160. """
  161. App.log.info("FlatCAM Starting...")
  162. self.main_thread = QtWidgets.QApplication.instance().thread()
  163. # ############################################################################
  164. # # ################# OS-specific ############################################
  165. # ############################################################################
  166. portable = False
  167. # Folder for user settings.
  168. if sys.platform == 'win32':
  169. # #########################################################################
  170. # Setup the listening thread for another instance launching with args #####
  171. # #########################################################################
  172. # make sure the thread is stored by using a self. otherwise it's garbage collected
  173. self.th = QtCore.QThread()
  174. self.th.start(priority=QtCore.QThread.LowestPriority)
  175. self.new_launch = ArgsThread()
  176. self.new_launch.open_signal[list].connect(self.on_startup_args)
  177. self.new_launch.moveToThread(self.th)
  178. self.new_launch.start.emit()
  179. from win32com.shell import shell, shellcon
  180. if platform.architecture()[0] == '32bit':
  181. App.log.debug("Win32!")
  182. else:
  183. App.log.debug("Win64!")
  184. # #########################################################################
  185. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  186. # #########################################################################
  187. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  188. try:
  189. with open(config_file, 'r') as f:
  190. try:
  191. for line in f:
  192. param = str(line).rpartition('=')
  193. if param[0] == 'portable':
  194. try:
  195. portable = eval(param[2])
  196. except NameError:
  197. portable = False
  198. except Exception as e:
  199. log.debug('App.__init__() -->%s' % str(e))
  200. return
  201. except FileNotFoundError:
  202. pass
  203. if portable is False:
  204. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  205. else:
  206. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  207. self.os = 'windows'
  208. else: # Linux/Unix/MacOS
  209. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  210. self.os = 'unix'
  211. # ##########################################################################
  212. # ################## Setup folders and files ###############################
  213. # ##########################################################################
  214. if not os.path.exists(self.data_path):
  215. os.makedirs(self.data_path)
  216. App.log.debug('Created data folder: ' + self.data_path)
  217. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  218. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  219. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  220. if not os.path.exists(self.postprocessorpaths):
  221. os.makedirs(self.postprocessorpaths)
  222. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  223. # create current_defaults.FlatConfig file if there is none
  224. try:
  225. f = open(self.data_path + '/current_defaults.FlatConfig')
  226. f.close()
  227. except IOError:
  228. App.log.debug('Creating empty current_defaults.FlatConfig')
  229. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  230. json.dump({}, f)
  231. f.close()
  232. # create factory_defaults.FlatConfig file if there is none
  233. try:
  234. f = open(self.data_path + '/factory_defaults.FlatConfig')
  235. f.close()
  236. except IOError:
  237. App.log.debug('Creating empty factory_defaults.FlatConfig')
  238. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  239. json.dump({}, f)
  240. f.close()
  241. try:
  242. f = open(self.data_path + '/recent.json')
  243. f.close()
  244. except IOError:
  245. App.log.debug('Creating empty recent.json')
  246. f = open(self.data_path + '/recent.json', 'w')
  247. json.dump([], f)
  248. f.close()
  249. try:
  250. fp = open(self.data_path + '/recent_projects.json')
  251. fp.close()
  252. except IOError:
  253. App.log.debug('Creating empty recent_projects.json')
  254. fp = open(self.data_path + '/recent_projects.json', 'w')
  255. json.dump([], fp)
  256. fp.close()
  257. # Application directory. CHDIR to it. Otherwise, trying to load
  258. # GUI icons will fail as their path is relative.
  259. # This will fail under cx_freeze ...
  260. self.app_home = os.path.dirname(os.path.realpath(__file__))
  261. App.log.debug("Application path is " + self.app_home)
  262. App.log.debug("Started in " + os.getcwd())
  263. # cx_freeze workaround
  264. if os.path.isfile(self.app_home):
  265. self.app_home = os.path.dirname(self.app_home)
  266. os.chdir(self.app_home)
  267. # #############################################################################
  268. # ##################### CREATE MULTIPROCESSING POOL ###########################
  269. # #############################################################################
  270. self.pool = Pool()
  271. # ##########################################################################
  272. # ################## Setting the Splash Screen #############################
  273. # ##########################################################################
  274. settings = QSettings("Open Source", "FlatCAM")
  275. if settings.contains("splash_screen"):
  276. show_splash = settings.value("splash_screen")
  277. else:
  278. settings.setValue('splash_screen', 1)
  279. # This will write the setting to the platform specific storage.
  280. del settings
  281. show_splash = 1
  282. if show_splash:
  283. splash_pix = QtGui.QPixmap('share/splash.png')
  284. splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  285. # splash.setMask(splash_pix.mask())
  286. splash.show()
  287. splash.showMessage(_("FlatCAM is initializing ..."),
  288. alignment=Qt.AlignBottom | Qt.AlignLeft,
  289. color=QtGui.QColor("gray"))
  290. # #############################################################################
  291. # ##################### Initialize GUI ########################################
  292. # #############################################################################
  293. # FlatCAM colors used in plotting
  294. self.FC_light_green = '#BBF268BF'
  295. self.FC_dark_green = '#006E20BF'
  296. self.FC_light_blue = '#a5a5ffbf'
  297. self.FC_dark_blue = '#0000ffbf'
  298. QtCore.QObject.__init__(self)
  299. self.ui = FlatCAMGUI(self.version, self.beta, self)
  300. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  301. self.ui.final_save.connect(self.final_save)
  302. # #############################################################################
  303. # ############################## Data #########################################
  304. # #############################################################################
  305. self.recent = []
  306. self.recent_projects = []
  307. self.clipboard = QtWidgets.QApplication.clipboard()
  308. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  309. self.project_filename = None
  310. self.toggle_units_ignore = False
  311. # self.defaults_form = PreferencesUI()
  312. # when adding entries here read the comments in the method found bellow named:
  313. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  314. self.defaults_form_fields = {
  315. # General App
  316. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  317. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  318. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  319. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  320. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  321. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  322. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  323. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  324. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  325. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  326. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  327. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  328. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  329. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  330. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  331. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  332. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  333. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  334. # General GUI Preferences
  335. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  336. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  337. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  338. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  339. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  340. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  341. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  342. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  343. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  344. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  345. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  346. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  347. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  348. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  349. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  350. # General GUI Settings
  351. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  352. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  353. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  354. # Gerber General
  355. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  356. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  357. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  358. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  359. "gerber_buffering": self.ui.gerber_defaults_form.gerber_gen_group.buffering_radio,
  360. "gerber_simplification": self.ui.gerber_defaults_form.gerber_gen_group.simplify_cb,
  361. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_gen_group.simplification_tol_spinner,
  362. # Gerber Options
  363. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  364. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  365. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  366. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  367. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  368. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  369. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  370. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  371. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  372. # Gerber Advanced Options
  373. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  374. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  375. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  376. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  377. # Gerber Export
  378. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  379. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  380. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  381. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  382. # Gerber Editor
  383. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  384. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  385. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  386. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  387. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  388. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  389. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  390. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  391. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  392. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  393. "gerber_editor_circ_angle":
  394. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  395. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  396. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  397. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  398. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  399. # Excellon General
  400. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  401. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  402. "excellon_format_upper_in":
  403. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  404. "excellon_format_lower_in":
  405. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  406. "excellon_format_upper_mm":
  407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  408. "excellon_format_lower_mm":
  409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  410. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  411. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  412. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  413. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  414. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  415. # Excellon Options
  416. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  417. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  418. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  419. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  420. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  421. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  422. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  423. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  424. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  425. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  426. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  427. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  428. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  429. # Excellon Advanced Options
  430. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  431. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  432. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  433. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  434. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  435. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  436. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  437. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  438. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  439. # Excellon Export
  440. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  441. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  442. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  443. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  444. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  445. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  446. # Excellon Editor
  447. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  448. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  449. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  450. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  451. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  452. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  453. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  454. "excellon_editor_circ_angle":
  455. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  456. # Excellon Slots
  457. "excellon_editor_slot_direction":
  458. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  459. "excellon_editor_slot_angle":
  460. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  461. "excellon_editor_slot_length":
  462. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  463. # Excellon Slots
  464. "excellon_editor_slot_array_size":
  465. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  466. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  467. "excellon_editor_slot_lin_pitch":
  468. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  469. "excellon_editor_slot_lin_angle":
  470. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  471. "excellon_editor_slot_circ_dir":
  472. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  473. "excellon_editor_slot_circ_angle":
  474. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  475. # Geometry General
  476. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  477. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  478. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  479. # Geometry Options
  480. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  481. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  482. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  483. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  484. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  485. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  486. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  487. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  488. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  489. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  490. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  491. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  492. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  493. # Geometry Advanced Options
  494. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  495. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  496. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  497. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  498. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  499. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  500. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  501. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  502. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  503. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  504. # Geometry Editor
  505. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  506. # CNCJob General
  507. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  508. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  509. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  510. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  511. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  512. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  513. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  514. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  515. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  516. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  517. # CNC Job Options
  518. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  519. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  520. # CNC Job Advanced Options
  521. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  522. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  523. # NCC Tool
  524. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  525. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  526. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  527. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  528. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  529. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  530. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  531. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  532. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  533. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  534. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  535. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  536. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  537. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  538. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  539. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  540. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  541. # CutOut Tool
  542. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  543. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  544. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  545. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  546. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  547. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  548. # Paint Area Tool
  549. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  550. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  551. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  552. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  553. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  554. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  555. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  556. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  557. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  558. # 2-sided Tool
  559. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  560. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  561. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  562. # Film Tool
  563. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  564. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  565. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  566. # Panelize Tool
  567. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  568. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  569. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  570. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  571. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  572. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  573. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  574. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  575. # Calculators Tool
  576. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  577. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  578. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  579. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  580. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  581. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  582. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  583. # Transformations Tool
  584. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  585. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  586. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  587. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  588. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  589. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  590. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  591. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  592. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  593. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  594. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  595. # SolderPaste Dispensing Tool
  596. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  597. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  598. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  599. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  600. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  601. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  602. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  603. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  604. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  605. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  606. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  607. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  608. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  609. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  610. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  611. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  612. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  613. # file associations
  614. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  615. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  616. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  617. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  618. }
  619. # ############################
  620. # ### LOAD POSTPROCESSORS ####
  621. # ############################
  622. self.postprocessors = load_postprocessors(self)
  623. for name in list(self.postprocessors.keys()):
  624. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  625. if name.partition('_')[0] == 'Paste':
  626. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  627. continue
  628. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  629. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  630. if name == 'hpgl':
  631. continue
  632. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  633. # ############################
  634. # ### LOAD LANGUAGES ####
  635. # ############################
  636. self.languages = fcTranslate.load_languages()
  637. for name in sorted(self.languages.values()):
  638. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  639. self.defaults = LoudDict()
  640. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  641. self.defaults.update({
  642. # Global APP Preferences
  643. "first_run": True,
  644. "units": "IN",
  645. "global_serial": 0,
  646. "global_stats": {},
  647. "global_tabs_detachable": True,
  648. "global_app_level": 'b',
  649. "global_portable": False,
  650. "global_language": 'English',
  651. "global_version_check": True,
  652. "global_send_stats": True,
  653. "global_pan_button": '2',
  654. "global_mselect_key": 'Control',
  655. "global_project_at_startup": False,
  656. "global_project_autohide": True,
  657. "global_toggle_tooltips": True,
  658. "global_worker_number": 2,
  659. "global_tolerance": 0.01,
  660. "global_open_style": True,
  661. "global_delete_confirmation": True,
  662. "global_compression_level": 3,
  663. "global_save_compressed": True,
  664. # Global GUI Preferences
  665. "global_gridx": 0.0393701,
  666. "global_gridy": 0.0393701,
  667. "global_snap_max": 0.001968504,
  668. "global_workspace": False,
  669. "global_workspaceT": "A4P",
  670. "global_grid_context_menu": {
  671. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  672. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  673. },
  674. "global_plot_fill": '#BBF268BF',
  675. "global_plot_line": '#006E20BF',
  676. "global_sel_fill": '#a5a5ffbf',
  677. "global_sel_line": '#0000ffbf',
  678. "global_alt_sel_fill": '#BBF268BF',
  679. "global_alt_sel_line": '#006E20BF',
  680. "global_draw_color": '#FF0000',
  681. "global_sel_draw_color": '#0000FF',
  682. "global_proj_item_color": '#000000',
  683. "global_proj_item_dis_color": '#b7b7cb',
  684. "global_toolbar_view": 511,
  685. "global_background_timeout": 300000, # Default value is 5 minutes
  686. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  687. # (python trace only for unknown errors),
  688. # 1 = show trace(show trace always),
  689. # 2 = (For the future).
  690. # Persistence
  691. "global_last_folder": None,
  692. "global_last_save_folder": None,
  693. # Default window geometry
  694. "global_def_win_x": 100,
  695. "global_def_win_y": 100,
  696. "global_def_win_w": 1024,
  697. "global_def_win_h": 650,
  698. "global_def_notebook_width": 1,
  699. # Constants...
  700. "global_defaults_save_period_ms": 20000, # Time between default saves.
  701. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  702. "global_shell_at_startup": False, # Show the shell at startup.
  703. "global_recent_limit": 10, # Max. items in recent list.
  704. "fit_key": 'V',
  705. "zoom_out_key": '-',
  706. "zoom_in_key": '=',
  707. "grid_toggle_key": 'G',
  708. "global_zoom_ratio": 1.5,
  709. "global_point_clipboard_format": "(%.4f, %.4f)",
  710. "global_zdownrate": None,
  711. # autocomplete keywords
  712. "global_autocomplete_keywords":
  713. ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  714. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  715. 'drilled_dias', 'drillz', 'pp',
  716. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  717. 'milled_dias',
  718. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  719. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  720. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  721. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  722. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  723. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  724. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy', 'iso_type',
  725. 'Desktop', 'FlatPrj', 'FlatConfig', 'Users', 'Documents', 'My Documents', 'Marius'
  726. ],
  727. # General GUI Settings
  728. "global_hover": False,
  729. "global_selection_shape": True,
  730. "global_layout": "compact",
  731. # Gerber General
  732. "gerber_plot": True,
  733. "gerber_solid": True,
  734. "gerber_multicolored": False,
  735. "gerber_circle_steps": 128,
  736. "gerber_use_buffer_for_union": True,
  737. "gerber_buffering": "full",
  738. "gerber_simplification": False,
  739. "gerber_simp_tolerance": 0.0005,
  740. # Gerber Options
  741. "gerber_isotooldia": 0.00787402,
  742. "gerber_isopasses": 1,
  743. "gerber_isooverlap": 0.00393701,
  744. "gerber_milling_type": "cl",
  745. "gerber_combine_passes": False,
  746. "gerber_noncoppermargin": 0.00393701,
  747. "gerber_noncopperrounded": False,
  748. "gerber_bboxmargin": 0.00393701,
  749. "gerber_bboxrounded": False,
  750. # Gerber Advanced Options
  751. "gerber_aperture_display": False,
  752. "gerber_aperture_scale_factor": 1.0,
  753. "gerber_aperture_buffer_factor": 0.0,
  754. "gerber_follow": False,
  755. # Gerber Export
  756. "gerber_exp_units": 'IN',
  757. "gerber_exp_integer": 2,
  758. "gerber_exp_decimals": 4,
  759. "gerber_exp_zeros": 'L',
  760. # Gerber Editor
  761. "gerber_editor_sel_limit": 30,
  762. "gerber_editor_newcode": 10,
  763. "gerber_editor_newsize": 0.8,
  764. "gerber_editor_newtype": 'C',
  765. "gerber_editor_newdim": "0.5, 0.5",
  766. "gerber_editor_array_size": 5,
  767. "gerber_editor_lin_axis": 'X',
  768. "gerber_editor_lin_pitch": 1,
  769. "gerber_editor_lin_angle": 0.0,
  770. "gerber_editor_circ_dir": 'CW',
  771. "gerber_editor_circ_angle": 0.0,
  772. "gerber_editor_scale_f": 1.0,
  773. "gerber_editor_buff_f": 0.1,
  774. "gerber_editor_ma_low": 0.0,
  775. "gerber_editor_ma_high": 1.0,
  776. # Excellon General
  777. "excellon_plot": True,
  778. "excellon_solid": True,
  779. "excellon_format_upper_in": 2,
  780. "excellon_format_lower_in": 4,
  781. "excellon_format_upper_mm": 3,
  782. "excellon_format_lower_mm": 3,
  783. "excellon_zeros": "L",
  784. "excellon_units": "INCH",
  785. "excellon_update": True,
  786. "excellon_optimization_type": 'B',
  787. "excellon_search_time": 3,
  788. # Excellon Options
  789. "excellon_drillz": -0.0590551,
  790. "excellon_travelz": 0.0787402,
  791. "excellon_feedrate": 3.14961,
  792. "excellon_spindlespeed": None,
  793. "excellon_spindledir": 'CW',
  794. "excellon_dwell": False,
  795. "excellon_dwelltime": 1,
  796. "excellon_toolchange": False,
  797. "excellon_toolchangez": 0.5,
  798. "excellon_ppname_e": 'default',
  799. "excellon_tooldia": 0.0314961,
  800. "excellon_slot_tooldia": 0.0708661,
  801. "excellon_gcode_type": "drills",
  802. # Excellon Advanced Options
  803. "excellon_offset": 0.0,
  804. "excellon_toolchangexy": "0.0, 0.0",
  805. "excellon_startz": None,
  806. "excellon_endz": 0.5,
  807. "excellon_feedrate_rapid": 31.4961,
  808. "excellon_z_pdepth": -0.02,
  809. "excellon_feedrate_probe": 3.14961,
  810. "excellon_f_plunge": False,
  811. "excellon_f_retract": False,
  812. # Excellon Export
  813. "excellon_exp_units": 'INCH',
  814. "excellon_exp_format": 'ndec',
  815. "excellon_exp_integer": 2,
  816. "excellon_exp_decimals": 4,
  817. "excellon_exp_zeros": 'LZ',
  818. "excellon_exp_slot_type": 'routing',
  819. # Excellon Editor
  820. "excellon_editor_sel_limit": 30,
  821. "excellon_editor_newdia": 0.039,
  822. "excellon_editor_array_size": 5,
  823. "excellon_editor_lin_dir": 'X',
  824. "excellon_editor_lin_pitch": 0.1,
  825. "excellon_editor_lin_angle": 0.0,
  826. "excellon_editor_circ_dir": 'CW',
  827. "excellon_editor_circ_angle": 12,
  828. # Excellon Slots
  829. "excellon_editor_slot_direction": 'X',
  830. "excellon_editor_slot_angle": 0.0,
  831. "excellon_editor_slot_length": 5.0,
  832. # Excellon Slot Array
  833. "excellon_editor_slot_array_size": 5,
  834. "excellon_editor_slot_lin_dir": 'X',
  835. "excellon_editor_slot_lin_pitch": 0.1,
  836. "excellon_editor_slot_lin_angle": 0.0,
  837. "excellon_editor_slot_circ_dir": 'CW',
  838. "excellon_editor_slot_circ_angle": 0.0,
  839. # Geometry General
  840. "geometry_plot": True,
  841. "geometry_circle_steps": 128,
  842. "geometry_cnctooldia": "0.0944882",
  843. # Geometry Options
  844. "geometry_cutz": -0.0944882,
  845. "geometry_vtipdia": 0.1,
  846. "geometry_vtipangle": 30,
  847. "geometry_multidepth": False,
  848. "geometry_depthperpass": 0.0314961,
  849. "geometry_travelz": 0.0787402,
  850. "geometry_toolchange": False,
  851. "geometry_toolchangez": 0.5,
  852. "geometry_feedrate": 3.14961,
  853. "geometry_feedrate_z": 3.14961,
  854. "geometry_spindlespeed": None,
  855. "geometry_spindledir": 'CW',
  856. "geometry_dwell": False,
  857. "geometry_dwelltime": 1,
  858. "geometry_ppname_g": 'default',
  859. # Geometry Advanced Options
  860. "geometry_toolchangexy": "0.0, 0.0",
  861. "geometry_startz": None,
  862. "geometry_endz": 0.5,
  863. "geometry_feedrate_rapid": 3.14961,
  864. "geometry_extracut": False,
  865. "geometry_z_pdepth": -0.02,
  866. "geometry_f_plunge": False,
  867. "geometry_feedrate_probe": 3.14961,
  868. "geometry_segx": 0.0,
  869. "geometry_segy": 0.0,
  870. # Geometry Editor
  871. "geometry_editor_sel_limit": 30,
  872. # CNC Job General
  873. "cncjob_plot": True,
  874. "cncjob_plot_kind": 'all',
  875. "cncjob_annotation": True,
  876. "cncjob_annotation_fontsize": 9,
  877. "cncjob_annotation_fontcolor": '#990000',
  878. "cncjob_tooldia": 0.0393701,
  879. "cncjob_coords_type": "G90",
  880. "cncjob_coords_decimals": 4,
  881. "cncjob_fr_decimals": 2,
  882. "cncjob_steps_per_circle": 128,
  883. # CNC Job Options
  884. "cncjob_prepend": "",
  885. "cncjob_append": "",
  886. # CNC Job Advanced Options
  887. "cncjob_toolchange_macro": "",
  888. "cncjob_toolchange_macro_enable": False,
  889. "tools_ncctools": "0.0393701, 0.019685",
  890. "tools_nccorder": 'rev',
  891. "tools_nccoverlap": 0.015748,
  892. "tools_nccmargin": 0.0393701,
  893. "tools_nccmethod": "seed",
  894. "tools_nccconnect": True,
  895. "tools_ncccontour": True,
  896. "tools_nccrest": False,
  897. "tools_ncc_offset_choice": False,
  898. "tools_ncc_offset_value": 0.0000,
  899. "tools_nccref": 'itself',
  900. "tools_ncc_plotting": 'normal',
  901. "tools_nccmilling_type": 'cl',
  902. "tools_ncctool_type": 'V',
  903. "tools_ncccutz": -0.001968504,
  904. "tools_ncctipdia": 0.00393701,
  905. "tools_ncctipangle": 30,
  906. "tools_cutouttooldia": 0.0944882,
  907. "tools_cutoutkind": "single",
  908. "tools_cutoutmargin": 0.00393701,
  909. "tools_cutoutgapsize": 0.15748,
  910. "tools_gaps_ff": "4",
  911. "tools_cutout_convexshape": False,
  912. "tools_painttooldia": 0.023622,
  913. "tools_paintorder": 'rev',
  914. "tools_paintoverlap": 0.015748,
  915. "tools_paintmargin": 0.0,
  916. "tools_paintmethod": "seed",
  917. "tools_selectmethod": "single",
  918. "tools_pathconnect": True,
  919. "tools_paintcontour": True,
  920. "tools_paint_plotting": 'normal',
  921. "tools_2sided_mirror_axis": "X",
  922. "tools_2sided_axis_loc": "point",
  923. "tools_2sided_drilldia": 0.0393701,
  924. "tools_film_type": 'neg',
  925. "tools_film_boundary": 0.0393701,
  926. "tools_film_scale": 0,
  927. "tools_panelize_spacing_columns": 0,
  928. "tools_panelize_spacing_rows": 0,
  929. "tools_panelize_columns": 1,
  930. "tools_panelize_rows": 1,
  931. "tools_panelize_constrain": False,
  932. "tools_panelize_constrainx": 0.0,
  933. "tools_panelize_constrainy": 0.0,
  934. "tools_panelize_panel_type": 'gerber',
  935. "tools_calc_vshape_tip_dia": 0.007874,
  936. "tools_calc_vshape_tip_angle": 30,
  937. "tools_calc_vshape_cut_z": 0.000787,
  938. "tools_calc_electro_length": 10.0,
  939. "tools_calc_electro_width": 10.0,
  940. "tools_calc_electro_cdensity": 13.0,
  941. "tools_calc_electro_growth": 10.0,
  942. "tools_transform_rotate": 90,
  943. "tools_transform_skew_x": 0.0,
  944. "tools_transform_skew_y": 0.0,
  945. "tools_transform_scale_x": 1.0,
  946. "tools_transform_scale_y": 1.0,
  947. "tools_transform_scale_link": True,
  948. "tools_transform_scale_reference": True,
  949. "tools_transform_offset_x": 0.0,
  950. "tools_transform_offset_y": 0.0,
  951. "tools_transform_mirror_reference": False,
  952. "tools_transform_mirror_point": (0, 0),
  953. "tools_solderpaste_tools": "0.0393701, 0.011811",
  954. "tools_solderpaste_new": 0.011811,
  955. "tools_solderpaste_z_start": 0.00019685039,
  956. "tools_solderpaste_z_dispense": 0.00393701,
  957. "tools_solderpaste_z_stop": 0.00019685039,
  958. "tools_solderpaste_z_travel": 0.00393701,
  959. "tools_solderpaste_z_toolchange": 0.0393701,
  960. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  961. "tools_solderpaste_frxy": 3.0,
  962. "tools_solderpaste_frz": 3.0,
  963. "tools_solderpaste_frz_dispense": 0.0393701,
  964. "tools_solderpaste_speedfwd": 20,
  965. "tools_solderpaste_dwellfwd": 1,
  966. "tools_solderpaste_speedrev": 10,
  967. "tools_solderpaste_dwellrev": 1,
  968. "tools_solderpaste_pp": 'Paste_1',
  969. "tools_sub_close_paths": True,
  970. # file associations
  971. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  972. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  973. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  974. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  975. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  976. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  977. })
  978. # ############################################################
  979. # ############### Load defaults from file ####################
  980. # ############################################################
  981. if user_defaults:
  982. self.load_defaults(filename='current_defaults')
  983. # #############################################################
  984. # ############## APPLY APP LANGUAGE ###########################
  985. # #############################################################
  986. ret_val = fcTranslate.apply_language('strings')
  987. if ret_val == "no language":
  988. self.inform.emit('[ERROR] %s' %
  989. _("Could not find the Language files. The App strings are missing."))
  990. log.debug("Could not find the Language files. The App strings are missing.")
  991. else:
  992. # make the current language the current selection on the language combobox
  993. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  994. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  995. # ##############################################################
  996. # ################# CREATE UNIQUE SERIAL NUMBER ################
  997. # ##############################################################
  998. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  999. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1000. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1001. self.save_defaults(silent=True)
  1002. self.propagate_defaults(silent=True)
  1003. self.restore_main_win_geom()
  1004. def auto_save_defaults():
  1005. try:
  1006. self.save_defaults(silent=True)
  1007. self.propagate_defaults(silent=True)
  1008. finally:
  1009. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1010. # the following lines activates automatic defaults save
  1011. # if user_defaults:
  1012. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1013. # self.options_form = PreferencesUI()
  1014. self.options_form_fields = {
  1015. "units": self.ui.general_options_form.general_app_group.units_radio,
  1016. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1017. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1018. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1019. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1020. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1021. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1022. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1023. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1024. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1025. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1026. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1027. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1028. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1029. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1030. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1031. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1032. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1033. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1034. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1035. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1036. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1037. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1038. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1039. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1040. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1041. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1042. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1043. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  1044. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1045. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1046. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1047. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1048. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1049. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1050. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1051. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1052. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1053. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1054. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  1055. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1056. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1057. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1058. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1059. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1060. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1061. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1062. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  1063. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1064. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1065. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1066. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1067. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1068. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1069. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1070. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1071. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1072. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1073. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1074. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1075. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1076. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  1077. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1078. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1079. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1080. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1081. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1082. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1083. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1084. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1085. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1086. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1087. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1088. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1089. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1090. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1091. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1092. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1093. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1094. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1095. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1096. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1097. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1098. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1099. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1100. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1101. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1102. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1103. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1104. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1105. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1106. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1107. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1108. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1109. }
  1110. for name in list(self.postprocessors.keys()):
  1111. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1112. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1113. self.options = LoudDict()
  1114. self.options.set_change_callback(self.on_options_dict_change)
  1115. self.options.update({
  1116. "units": "IN",
  1117. "global_gridx": 1.0,
  1118. "global_gridy": 1.0,
  1119. "global_snap_max": 0.05,
  1120. "global_background_timeout": 300000, # Default value is 5 minutes
  1121. "global_verbose_error_level": 0, # Shell verbosity:
  1122. # 0 = default(python trace only for unknown errors),
  1123. # 1 = show trace(show trace allways), 2 = (For the future).
  1124. "gerber_plot": True,
  1125. "gerber_solid": True,
  1126. "gerber_multicolored": False,
  1127. "gerber_isotooldia": 0.016,
  1128. "gerber_isopasses": 1,
  1129. "gerber_isooverlap": 0.15,
  1130. "gerber_combine_passes": True,
  1131. "gerber_noncoppermargin": 0.0,
  1132. "gerber_noncopperrounded": False,
  1133. "gerber_bboxmargin": 0.0,
  1134. "gerber_bboxrounded": False,
  1135. "excellon_plot": True,
  1136. "excellon_solid": False,
  1137. "excellon_format_upper_in": 2,
  1138. "excellon_format_lower_in": 4,
  1139. "excellon_format_upper_mm": 3,
  1140. "excellon_format_lower_mm": 3,
  1141. "excellon_units": 'INCH',
  1142. "excellon_optimization_type": 'B',
  1143. "excellon_search_time": 3,
  1144. "excellon_zeros": "L",
  1145. "excellon_drillz": -0.1,
  1146. "excellon_travelz": 0.1,
  1147. "excellon_feedrate": 3.0,
  1148. "excellon_feedrate_rapid": 3.0,
  1149. "excellon_spindlespeed": None,
  1150. "excellon_spindledir": 'CW',
  1151. "excellon_dwell": True,
  1152. "excellon_dwelltime": 1000,
  1153. "excellon_toolchange": False,
  1154. "excellon_toolchangez": 1.0,
  1155. "excellon_toolchangexy": "0.0, 0.0",
  1156. "excellon_tooldia": 0.016,
  1157. "excellon_ppname_e": 'default',
  1158. "excellon_f_plunge": False,
  1159. "excellon_startz": None,
  1160. "excellon_endz": 2.0,
  1161. "geometry_plot": True,
  1162. "geometry_segx": 0.0,
  1163. "geometry_segy": 0.0,
  1164. "geometry_cutz": -0.002,
  1165. "geometry_vtipdia": 0.1,
  1166. "geometry_vtipangle": 30,
  1167. "geometry_travelz": 0.1,
  1168. "geometry_feedrate": 3.0,
  1169. "geometry_feedrate_z": 3.0,
  1170. "geometry_feedrate_rapid": 3.0,
  1171. "geometry_spindlespeed": None,
  1172. "geometry_spindledir": 'CW',
  1173. "geometry_dwell": True,
  1174. "geometry_dwelltime": 1000,
  1175. "geometry_cnctooldia": 0.016,
  1176. "geometry_toolchange": False,
  1177. "geometry_toolchangez": 2.0,
  1178. "geometry_toolchangexy": "0.0, 0.0",
  1179. "geometry_startz": None,
  1180. "geometry_endz": 2.0,
  1181. "geometry_ppname_g": "default",
  1182. "geometry_f_plunge": False,
  1183. "geometry_depthperpass": 0.002,
  1184. "geometry_multidepth": False,
  1185. "geometry_extracut": False,
  1186. "cncjob_plot": True,
  1187. "cncjob_tooldia": 0.016,
  1188. "cncjob_prepend": "",
  1189. "cncjob_append": "",
  1190. "tools_ncctools": "1.0, 0.5",
  1191. "tools_nccoverlap": 0.4,
  1192. "tools_nccmargin": 1,
  1193. "tools_cutouttooldia": 0.07,
  1194. "tools_cutoutmargin": 0.1,
  1195. "tools_cutoutgapsize": 0.15,
  1196. "tools_gaps_ff": "8",
  1197. "tools_painttooldia": 0.07,
  1198. "tools_paintoverlap": 0.15,
  1199. "tools_paintmargin": 0.0,
  1200. "tools_paintmethod": "seed",
  1201. "tools_selectmethod": "single",
  1202. "tools_pathconnect": True,
  1203. "tools_paintcontour": True,
  1204. "tools_2sided_mirror_axis": "X",
  1205. "tools_2sided_axis_loc": 'point',
  1206. "tools_2sided_drilldia": 1,
  1207. "tools_film_type": 'neg',
  1208. "tools_film_boundary": 1,
  1209. "tools_film_scale": 0,
  1210. "tools_panelize_spacing_columns": 0,
  1211. "tools_panelize_spacing_rows": 0,
  1212. "tools_panelize_columns": 1,
  1213. "tools_panelize_rows": 1,
  1214. "tools_panelize_constrain": False,
  1215. "tools_panelize_constrainx": 0.0,
  1216. "tools_panelize_constrainy": 0.0
  1217. })
  1218. self.options.update(self.defaults) # Copy app defaults to project options
  1219. self.gen_form = None
  1220. self.ger_form = None
  1221. self.exc_form = None
  1222. self.geo_form = None
  1223. self.cnc_form = None
  1224. self.tools_form = None
  1225. self.fa_form = None
  1226. self.on_options_combo_change(0) # Will show the initial form
  1227. # ################################
  1228. # ### Initialize the color box's color in Preferences -> Global -> Color
  1229. # Init Plot Colors
  1230. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1231. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1232. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1233. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1234. int(self.defaults['global_plot_fill'][7:9], 16))
  1235. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1236. int(self.defaults['global_plot_fill'][7:9], 16))
  1237. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1238. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1239. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1240. # Init Left-Right Selection colors
  1241. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1242. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1243. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1244. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1245. int(self.defaults['global_sel_fill'][7:9], 16))
  1246. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1247. int(self.defaults['global_sel_fill'][7:9], 16))
  1248. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1249. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1250. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1251. # Init Right-Left Selection colors
  1252. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1253. self.defaults['global_alt_sel_fill'])
  1254. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1255. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1256. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1257. int(self.defaults['global_sel_fill'][7:9], 16))
  1258. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1259. int(self.defaults['global_sel_fill'][7:9], 16))
  1260. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1261. self.defaults['global_alt_sel_line'])
  1262. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1263. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1264. # Init Draw color and Selection Draw Color
  1265. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1266. self.defaults['global_draw_color'])
  1267. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1268. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1269. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1270. self.defaults['global_sel_draw_color'])
  1271. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1272. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1273. # Init Project Items color
  1274. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1275. self.defaults['global_proj_item_color'])
  1276. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1277. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1278. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1279. self.defaults['global_proj_item_dis_color'])
  1280. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1281. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1282. # Init the Annotation CNC Job color
  1283. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1284. self.defaults['cncjob_annotation_fontcolor'])
  1285. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1286. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1287. # ### End of Data ####
  1288. # ###############################################
  1289. # ############# SETUP Plot Area #################
  1290. # ###############################################
  1291. if show_splash:
  1292. splash.showMessage(_("FlatCAM is initializing ...\n"
  1293. "Canvas initialization started."),
  1294. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1295. color=QtGui.QColor("gray"))
  1296. start_plot_time = time.time() # debug
  1297. self.plotcanvas = None
  1298. self.app_cursor = None
  1299. self.hover_shapes = None
  1300. self.on_plotcanvas_setup()
  1301. end_plot_time = time.time()
  1302. used_time = end_plot_time - start_plot_time
  1303. self.log.debug("Finished Canvas initialization in %s seconds." % str(used_time))
  1304. if show_splash:
  1305. splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1306. "Canvas initialization started.\n"
  1307. "Canvas initialization finished in"), '%.2f' % used_time),
  1308. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1309. color=QtGui.QColor("gray"))
  1310. self.ui.splitter.setStretchFactor(1, 2)
  1311. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1312. # depending on from where those tools are called different actions can be done
  1313. self.call_source = 'app'
  1314. # ##############################################
  1315. # ######### SETUP OBJECT COLLECTION ############
  1316. # ##############################################
  1317. self.collection = ObjectCollection(self)
  1318. self.ui.project_tab_layout.addWidget(self.collection.view)
  1319. # ### Adjust tabs width ## ##
  1320. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1321. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1322. self.collection.view.setMinimumWidth(290)
  1323. self.log.debug("Finished creating Object Collection.")
  1324. # ###############################################
  1325. # ############# Worker SETUP ####################
  1326. # ###############################################
  1327. if self.defaults["global_worker_number"]:
  1328. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1329. else:
  1330. self.workers = WorkerStack(workers_number=2)
  1331. self.worker_task.connect(self.workers.add_task)
  1332. self.log.debug("Finished creating Workers crew.")
  1333. # ################################################
  1334. # ############### Signal handling ################
  1335. # ################################################
  1336. # ############# Custom signals ##################
  1337. # signal for displaying messages in status bar
  1338. self.inform.connect(self.info)
  1339. # signal to be called when the app is quiting
  1340. self.app_quit.connect(self.quit_application)
  1341. self.message.connect(self.message_dialog)
  1342. self.progress.connect(self.set_progress_bar)
  1343. # signals that are emitted when object state changes
  1344. self.object_created.connect(self.on_object_created)
  1345. self.object_changed.connect(self.on_object_changed)
  1346. self.object_plotted.connect(self.on_object_plotted)
  1347. self.plots_updated.connect(self.on_plots_updated)
  1348. # signals emitted when file state change
  1349. self.file_opened.connect(self.register_recent)
  1350. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1351. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1352. # ############# Standard signals ###################
  1353. # ### Menu
  1354. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1355. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1356. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1357. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1358. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1359. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1360. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1361. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1362. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1363. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1364. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1365. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1366. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1367. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1368. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1369. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1370. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1371. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1372. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1373. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1374. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1375. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1376. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1377. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1378. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1379. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1380. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1381. self.ui.menufile_exit.triggered.connect(self.final_save)
  1382. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1383. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1384. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1385. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1386. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1387. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1388. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1389. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1390. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1391. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1392. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1393. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1394. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1395. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1396. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1397. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1398. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1399. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1400. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1401. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1402. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1403. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1404. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1405. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1406. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1407. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1408. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1409. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1410. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1411. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1412. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1413. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1414. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1415. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1416. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1417. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1418. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1419. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1420. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1421. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1422. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1423. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1424. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1425. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1426. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1427. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1428. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1429. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1430. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1431. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1432. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1433. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1434. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1435. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1436. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1437. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1438. # ToolBar signals
  1439. self.connect_toolbar_signals()
  1440. # Notebook signals
  1441. # make the right click on the notebook tab connect to a function
  1442. self.ui.notebook.setupContextMenu()
  1443. self.ui.notebook.addContextMenu(
  1444. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1445. initial_checked=self.defaults["global_tabs_detachable"])
  1446. # activate initial state
  1447. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1448. # Context Menu
  1449. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1450. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1451. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1452. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1453. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1454. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1455. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1456. self.ui.clearplot.triggered.connect(self.clear_plots)
  1457. self.ui.replot.triggered.connect(self.plot_all)
  1458. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1459. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1460. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1461. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1462. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1463. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1464. # Preferences Plot Area TAB
  1465. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1466. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1467. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1468. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1469. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1470. # ##############################
  1471. # ### GUI PREFERENCES SIGNALS ##
  1472. # ##############################
  1473. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1474. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1475. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1476. )
  1477. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1478. lambda: self.on_toggle_units(no_pref=False))
  1479. # ###############################################################
  1480. # ################### GUI COLORS SIGNALS ########################
  1481. # ###############################################################
  1482. # Setting plot colors signals
  1483. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1484. self.on_pf_color_entry)
  1485. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1486. self.on_pf_color_button)
  1487. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1488. self.on_pf_color_spinner)
  1489. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1490. self.on_pf_color_slider)
  1491. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1492. self.on_pl_color_entry)
  1493. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1494. self.on_pl_color_button)
  1495. # Setting selection (left - right) colors signals
  1496. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1497. self.on_sf_color_entry)
  1498. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1499. self.on_sf_color_button)
  1500. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1501. self.on_sf_color_spinner)
  1502. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1503. self.on_sf_color_slider)
  1504. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1505. self.on_sl_color_entry)
  1506. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1507. self.on_sl_color_button)
  1508. # Setting selection (right - left) colors signals
  1509. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1510. self.on_alt_sf_color_entry)
  1511. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1512. self.on_alt_sf_color_button)
  1513. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1514. self.on_alt_sf_color_spinner)
  1515. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1516. self.on_alt_sf_color_slider)
  1517. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1518. self.on_alt_sl_color_entry)
  1519. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1520. self.on_alt_sl_color_button)
  1521. # Setting Editor Draw colors signals
  1522. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1523. self.on_draw_color_entry)
  1524. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1525. self.on_draw_color_button)
  1526. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1527. self.on_sel_draw_color_entry)
  1528. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1529. self.on_sel_draw_color_button)
  1530. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1531. self.on_proj_color_entry)
  1532. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1533. self.on_proj_color_button)
  1534. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1535. self.on_proj_color_dis_entry)
  1536. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1537. self.on_proj_color_dis_button)
  1538. # ########## workspace setting signals ###########
  1539. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1540. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1541. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1542. # ########## CNC Job related signals #############
  1543. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1544. self.on_cnc_custom_parameters)
  1545. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1546. self.on_annotation_fontcolor_entry)
  1547. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1548. self.on_annotation_fontcolor_button)
  1549. # ########## Modify G-CODE Plot Area TAB ###########
  1550. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1551. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1552. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1553. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1554. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1555. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1556. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1557. # portability changed signal
  1558. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1559. # Object list
  1560. self.collection.view.activated.connect(self.on_row_activated)
  1561. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1562. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1563. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1564. # Export Excellon parameters.
  1565. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1566. self.on_update_exc_export
  1567. )
  1568. # call it once to make sure it is updated at startup
  1569. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1570. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1571. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1572. self.on_excellon_defaults_button)
  1573. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1574. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1575. self.on_excellon_options_button)
  1576. # when there are arguments at application startup this get launched
  1577. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1578. # connect the 'Apply' buttons from the Preferences/File Associations
  1579. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1580. lambda: self.on_register_files(obj_type='excellon'))
  1581. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1582. lambda: self.on_register_files(obj_type='gcode'))
  1583. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1584. lambda: self.on_register_files(obj_type='gerber'))
  1585. # splash screen button signal
  1586. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1587. # connect the abort_all_tasks related slots to the related signals
  1588. self.proc_container.idle_flag.connect(self.app_is_idle)
  1589. # #####################################################################################
  1590. # ########### FINISHED CONNECTING SIGNALS #############################################
  1591. # #####################################################################################
  1592. self.log.debug("Finished connecting Signals.")
  1593. # #####################################################################################
  1594. # ########################## Other setups #############################################
  1595. # #####################################################################################
  1596. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1597. self.tool_tab_locked = False
  1598. # decide if to show or hide the Notebook side of the screen at startup
  1599. if self.defaults["global_project_at_startup"] is True:
  1600. self.ui.splitter.setSizes([1, 1])
  1601. else:
  1602. self.ui.splitter.setSizes([0, 1])
  1603. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1604. self.setup_obj_classes()
  1605. self.setup_recent_items()
  1606. self.setup_component_editor()
  1607. # #####################################################################################
  1608. # ######################### Auto-complete KEYWORDS ####################################
  1609. # #####################################################################################
  1610. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1611. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1612. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1613. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1614. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1615. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1616. 'mirror', 'ncc',
  1617. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1618. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1619. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'save', 'save_project',
  1620. 'save_sys', 'scale',
  1621. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1622. 'version', 'write_gcode'
  1623. ]
  1624. self.ordinary_keywords = self.defaults["global_autocomplete_keywords"]
  1625. self.tcl_keywords = [
  1626. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1627. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1628. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1629. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1630. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1631. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1632. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1633. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1634. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1635. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1636. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1637. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1638. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1639. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1640. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1641. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1642. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1643. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1644. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1645. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1646. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1647. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1648. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1649. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1650. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1651. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1652. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1653. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1654. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1655. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1656. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1657. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1658. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1659. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1660. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1661. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1662. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1663. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1664. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1665. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1666. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1667. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1668. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1669. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1670. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1671. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1672. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1673. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1674. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1675. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1676. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1677. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1678. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1679. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1680. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1681. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1682. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1683. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1684. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1685. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1686. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1687. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1688. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1689. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1690. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1691. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1692. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1693. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1694. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1695. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1696. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1697. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1698. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1699. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1700. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1701. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1702. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1703. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1704. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1705. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1706. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1707. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1708. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1709. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1710. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1711. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1712. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1713. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1714. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1715. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1716. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1717. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1718. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1719. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1720. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1721. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1722. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1723. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1724. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1725. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1726. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1727. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1728. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1729. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1730. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1731. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1732. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1733. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1734. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1735. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1736. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1737. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1738. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1739. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1740. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1741. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1742. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1743. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1744. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1745. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1746. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1747. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1748. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1749. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1750. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1751. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1752. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1753. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1754. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1755. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1756. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1757. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1758. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1759. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1760. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1761. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1762. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1763. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1764. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1765. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1766. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1767. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1768. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1769. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1770. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1771. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1772. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1773. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1774. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1775. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1776. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1777. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1778. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1779. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1780. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1781. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1782. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1783. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1784. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1785. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1786. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1787. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1788. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1789. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1790. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1791. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1792. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1793. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1794. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1795. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1796. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1797. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1798. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1799. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1800. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1801. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1802. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1803. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1804. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1805. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1806. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1807. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1808. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1809. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1810. ]
  1811. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1812. # ####################################################################################
  1813. # ####################### Shell SETUP ################################################
  1814. # ####################################################################################
  1815. self.shell = FCShell(self, version=self.version)
  1816. self.shell._edit.set_model_data(self.myKeywords)
  1817. self.ui.code_editor.set_model_data(self.myKeywords)
  1818. self.shell.setWindowIcon(self.ui.app_icon)
  1819. self.shell.setWindowTitle("FlatCAM Shell")
  1820. self.shell.resize(*self.defaults["global_shell_shape"])
  1821. self.shell.append_output("FlatCAM %s - " % self.version)
  1822. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1823. self.init_tcl()
  1824. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1825. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1826. self.ui.shell_dock.setWidget(self.shell)
  1827. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1828. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1829. QtWidgets.QDockWidget.DockWidgetFloatable |
  1830. QtWidgets.QDockWidget.DockWidgetClosable)
  1831. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1832. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1833. if self.defaults["global_shell_at_startup"]:
  1834. self.ui.shell_dock.show()
  1835. else:
  1836. self.ui.shell_dock.hide()
  1837. # ##################################################################################
  1838. # ###################### Tools and Plugins #########################################
  1839. # ##################################################################################
  1840. self.dblsidedtool = None
  1841. self.measurement_tool = None
  1842. self.panelize_tool = None
  1843. self.film_tool = None
  1844. self.paste_tool = None
  1845. self.calculator_tool = None
  1846. self.sub_tool = None
  1847. self.move_tool = None
  1848. self.cutout_tool = None
  1849. self.ncclear_tool = None
  1850. self.paint_tool = None
  1851. self.transform_tool = None
  1852. self.properties_tool = None
  1853. self.pdf_tool = None
  1854. self.image_tool = None
  1855. self.pcb_wizard_tool = None
  1856. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1857. self.install_tools()
  1858. # ### System Font Parsing ###
  1859. # self.f_parse = ParseFont(self)
  1860. # self.parse_system_fonts()
  1861. # #####################################################################################
  1862. # ########################## START-UP ARGUMENTS #######################################
  1863. # #####################################################################################
  1864. # test if the program was started with a script as parameter
  1865. if self.cmd_line_shellfile:
  1866. try:
  1867. with open(self.cmd_line_shellfile, "r") as myfile:
  1868. cmd_line_shellfile_text = myfile.read()
  1869. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1870. except Exception as ext:
  1871. print("ERROR: ", ext)
  1872. sys.exit(2)
  1873. # #####################################################################################
  1874. # ######################## Check for updates ##########################################
  1875. # #####################################################################################
  1876. # Separate thread (Not worker)
  1877. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1878. if (self.beta is False or self.beta is None) and \
  1879. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1880. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1881. self.thr2 = QtCore.QThread()
  1882. self.worker_task.emit({'fcn': self.version_check,
  1883. 'params': []})
  1884. self.thr2.start(QtCore.QThread.LowPriority)
  1885. # #####################################################################################
  1886. # ###################### Variables for global usage ###################################
  1887. # #####################################################################################
  1888. # register files with FlatCAM; it works only for Windows for now
  1889. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1890. self.on_register_files()
  1891. # coordinates for relative position display
  1892. self.rel_point1 = (0, 0)
  1893. self.rel_point2 = (0, 0)
  1894. # variable to store coordinates
  1895. self.pos = (0, 0)
  1896. self.pos_jump = (0, 0)
  1897. # variable to store mouse coordinates
  1898. self.mouse = [0, 0]
  1899. # decide if we have a double click or single click
  1900. self.doubleclick = False
  1901. # variable to store if a command is active (then the var is not None) and which one it is
  1902. self.command_active = None
  1903. # variable to store the status of moving selection action
  1904. # None value means that it's not an selection action
  1905. # True value = a selection from left to right
  1906. # False value = a selection from right to left
  1907. self.selection_type = None
  1908. # List to store the objects that are currently loaded in FlatCAM
  1909. # This list is updated on each object creation or object delete
  1910. self.all_objects_list = []
  1911. # List to store the objects that are selected
  1912. self.sel_objects_list = []
  1913. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1914. self.key_modifiers = None
  1915. # Variable to hold the status of the axis
  1916. self.toggle_axis = True
  1917. # Variable to store the status of the fullscreen event
  1918. self.toggle_fscreen = False
  1919. # Variable to store the status of the code editor
  1920. self.toggle_codeeditor = False
  1921. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1922. self.click_noproject = False
  1923. self.cursor = None
  1924. # Variable to store the GCODE that was edited
  1925. self.gcode_edited = ""
  1926. # reference for the self.ui.code_editor
  1927. self.reference_code_editor = None
  1928. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1929. self.preferences_changed_flag = False
  1930. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1931. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1932. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1933. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1934. ]
  1935. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1936. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1937. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1938. 'mpf'
  1939. ]
  1940. self.svg_list = ['svg']
  1941. self.dxf_list = ['dxf']
  1942. self.pdf_list = ['pdf']
  1943. self.prj_list = ['flatprj']
  1944. self.conf_list = ['flatconfig']
  1945. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1946. # flag for polygons not cleared
  1947. self.poly_not_cleared = False
  1948. # VisPy visuals
  1949. self.isHovering = False
  1950. self.notHovering = True
  1951. # when True, the app has to return from any thread
  1952. self.abort_flag = False
  1953. # ###############################################################################
  1954. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1955. # ############# It's done only once after install ###############
  1956. # ###############################################################################
  1957. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1958. fac_def_from_file = factory_file.read()
  1959. factory_defaults = json.loads(fac_def_from_file)
  1960. # if the file contain an empty dictionary then save the factory defaults into the file
  1961. if not factory_defaults:
  1962. self.save_factory_defaults(silent=False)
  1963. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1964. initial_lay = 'compact'
  1965. self.on_layout(lay=initial_lay)
  1966. # Set the combobox in Preferences to the current layout
  1967. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1968. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1969. factory_file.close()
  1970. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1971. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1972. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1973. # after the first run, this object should be False
  1974. self.defaults["first_run"] = False
  1975. # ###############################################################################
  1976. # ################# ADDING FlatCAM EDITORS section ##############################
  1977. # ###############################################################################
  1978. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1979. # at the first launch of the App , the editors will not be functional.
  1980. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1981. self.exc_editor = FlatCAMExcEditor(self)
  1982. self.grb_editor = FlatCAMGrbEditor(self)
  1983. self.log.debug("Finished adding FlatCAM Editor's.")
  1984. self.set_ui_title(name=_("New Project - Not saved"))
  1985. # finish the splash
  1986. # splash.finish(self.ui)
  1987. # ###############################################################################
  1988. # ####################### Finished the CONSTRUCTOR ##############################
  1989. # ###############################################################################
  1990. App.log.debug("END of constructor. Releasing control.")
  1991. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1992. # the path/file_name must be enclosed in quotes if it contain spaces
  1993. if App.args:
  1994. self.args_at_startup.emit(App.args)
  1995. @staticmethod
  1996. def copy_and_overwrite(from_path, to_path):
  1997. """
  1998. From here:
  1999. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2000. :param from_path: source path
  2001. :param to_path: destination path
  2002. :return: None
  2003. """
  2004. if os.path.exists(to_path):
  2005. shutil.rmtree(to_path)
  2006. try:
  2007. shutil.copytree(from_path, to_path)
  2008. except FileNotFoundError:
  2009. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2010. shutil.copytree(from_new_path, to_path)
  2011. def on_startup_args(self, args=None):
  2012. """
  2013. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2014. :param args: a list containing the application args at startup
  2015. :return: None
  2016. """
  2017. if args:
  2018. args_to_process = args
  2019. else:
  2020. args_to_process = App.args
  2021. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2022. for argument in args_to_process:
  2023. if '.FlatPrj' in argument:
  2024. try:
  2025. project_name = str(argument)
  2026. if project_name == "":
  2027. self.inform.emit(_("Open cancelled."))
  2028. else:
  2029. # self.open_project(project_name)
  2030. run_from_arg = True
  2031. # self.worker_task.emit({'fcn': self.open_project,
  2032. # 'params': [project_name, run_from_arg]})
  2033. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2034. except Exception as e:
  2035. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2036. elif '.FlatConfig' in argument:
  2037. try:
  2038. file_name = str(argument)
  2039. if file_name == "":
  2040. self.inform.emit(_("Open Config file failed."))
  2041. else:
  2042. # run_from_arg = True
  2043. # self.worker_task.emit({'fcn': self.open_config_file,
  2044. # 'params': [file_name, run_from_arg]})
  2045. self.open_config_file(file_name, run_from_arg=True)
  2046. except Exception as e:
  2047. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2048. elif '.FlatScript' in argument:
  2049. try:
  2050. file_name = str(argument)
  2051. if file_name == "":
  2052. self.inform.emit(_("Open Script file failed."))
  2053. else:
  2054. # run_from_arg = True
  2055. # self.worker_task.emit({'fcn': self.open_script_file,
  2056. # 'params': [file_name, run_from_arg]})
  2057. self.on_filerunscript(name=file_name)
  2058. except Exception as e:
  2059. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2060. else:
  2061. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2062. proc_arg = argument.lower()
  2063. for ext in exc_list:
  2064. proc_ext = ext.replace(' ', '')
  2065. if proc_ext.lower() in proc_arg and proc_ext != '':
  2066. file_name = str(argument)
  2067. if file_name == "":
  2068. self.inform.emit(_("Open Excellon file failed."))
  2069. else:
  2070. self.on_fileopenexcellon(name=file_name)
  2071. return
  2072. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2073. for ext in gco_list:
  2074. proc_ext = ext.replace(' ', '')
  2075. if proc_ext.lower() in proc_arg and proc_ext != '':
  2076. file_name = str(argument)
  2077. if file_name == "":
  2078. self.inform.emit(_("Open GCode file failed."))
  2079. else:
  2080. self.on_fileopengcode(name=file_name)
  2081. return
  2082. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2083. for ext in grb_list:
  2084. proc_ext = ext.replace(' ', '')
  2085. if proc_ext.lower() in proc_arg and proc_ext != '':
  2086. file_name = str(argument)
  2087. if file_name == "":
  2088. self.inform.emit(_("Open Gerber file failed."))
  2089. else:
  2090. self.on_fileopengerber(name=file_name)
  2091. return
  2092. def set_ui_title(self, name):
  2093. """
  2094. Sets the title of the main window.
  2095. :param name: String that store the project path and project name
  2096. :return: None
  2097. """
  2098. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2099. (self.version,
  2100. ('BETA' if self.beta else ''),
  2101. platform.architecture()[0],
  2102. name)
  2103. )
  2104. def defaults_read_form(self):
  2105. """
  2106. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2107. :return: None
  2108. """
  2109. for option in self.defaults_form_fields:
  2110. try:
  2111. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2112. except Exception as e:
  2113. log.debug("App.defaults_read_form() --> %s" % str(e))
  2114. def defaults_write_form(self, factor=None, fl_units=None):
  2115. """
  2116. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2117. self.defaults dictionary.
  2118. :param factor: will apply a factor to the values that written in the GUI elements
  2119. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2120. :return: None
  2121. """
  2122. for option in self.defaults:
  2123. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2124. # try:
  2125. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2126. # except KeyError:
  2127. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2128. # # TODO: Rethink this?
  2129. # pass
  2130. def defaults_write_form_field(self, field, factor=None, units=None):
  2131. """
  2132. Basically it is the worker in the self.defaults_write_form()
  2133. :param field: the GUI element in Preferences GUI to be updated
  2134. :param factor: factor to be applied to the field parameter
  2135. :param units: current FLatCAM measuring units
  2136. :return: None, it updates GUI elements
  2137. """
  2138. try:
  2139. if factor is None:
  2140. if units is None:
  2141. self.defaults_form_fields[field].set_value(self.defaults[field])
  2142. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2143. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2144. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2145. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2146. else:
  2147. if units is None:
  2148. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2149. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2150. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2151. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2152. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2153. except KeyError:
  2154. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2155. # TODO: Rethink this?
  2156. pass
  2157. except AttributeError:
  2158. log.debug(field)
  2159. def clear_pool(self):
  2160. """
  2161. Clear the multiprocessing pool and calls garbage collector.
  2162. :return: None
  2163. """
  2164. self.pool.close()
  2165. self.pool = Pool()
  2166. self.pool_recreated.emit(self.pool)
  2167. gc.collect()
  2168. def install_tools(self):
  2169. """
  2170. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2171. Instantiation of the Tools classes.
  2172. The order that the tools are installed is important as they can depend on each other install position.
  2173. :return: None
  2174. """
  2175. self.dblsidedtool = DblSidedTool(self)
  2176. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2177. self.measurement_tool = Measurement(self)
  2178. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2179. self.panelize_tool = Panelize(self)
  2180. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2181. self.film_tool = Film(self)
  2182. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2183. self.paste_tool = SolderPaste(self)
  2184. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2185. self.calculator_tool = ToolCalculator(self)
  2186. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2187. self.sub_tool = ToolSub(self)
  2188. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2189. self.move_tool = ToolMove(self)
  2190. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2191. before=self.ui.menueditorigin)
  2192. self.cutout_tool = CutOut(self)
  2193. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2194. before=self.measurement_tool.menuAction)
  2195. self.ncclear_tool = NonCopperClear(self)
  2196. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2197. before=self.measurement_tool.menuAction, separator=True)
  2198. self.paint_tool = ToolPaint(self)
  2199. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2200. before=self.measurement_tool.menuAction, separator=True)
  2201. self.transform_tool = ToolTransform(self)
  2202. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2203. self.properties_tool = Properties(self)
  2204. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2205. self.pdf_tool = ToolPDF(self)
  2206. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2207. separator=True)
  2208. self.image_tool = ToolImage(self)
  2209. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2210. separator=True)
  2211. self.pcb_wizard_tool = PcbWizard(self)
  2212. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2213. self.log.debug("Tools are installed.")
  2214. def remove_tools(self):
  2215. """
  2216. Will remove all the actions in the Tool menu.
  2217. :return: None
  2218. """
  2219. for act in self.ui.menutool.actions():
  2220. self.ui.menutool.removeAction(act)
  2221. def init_tools(self):
  2222. """
  2223. Initialize the Tool tab in the notebook side of the central widget.
  2224. Remove the actions in the Tools menu.
  2225. Instantiate again the FlatCAM tools (plugins).
  2226. All this is required when changing the layout: standard, compact etc.
  2227. :return: None
  2228. """
  2229. log.debug("init_tools()")
  2230. # delete the data currently in the Tools Tab and the Tab itself
  2231. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2232. if widget is not None:
  2233. widget.deleteLater()
  2234. self.ui.notebook.removeTab(2)
  2235. # rebuild the Tools Tab
  2236. self.ui.tool_tab = QtWidgets.QWidget()
  2237. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2238. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2239. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2240. self.ui.tool_scroll_area = VerticalScrollArea()
  2241. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2242. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2243. # first remove all of them
  2244. self.remove_tools()
  2245. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2246. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2247. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2248. # third install all of them
  2249. self.install_tools()
  2250. self.log.debug("Tools are initialized.")
  2251. # def parse_system_fonts(self):
  2252. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2253. # 'params': []})
  2254. def connect_toolbar_signals(self):
  2255. """
  2256. Reconnect the signals to the actions in the toolbar.
  2257. This has to be done each time after the FlatCAM tools are removed/installed.
  2258. :return: None
  2259. """
  2260. # Toolbar
  2261. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2262. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2263. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2264. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2265. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2266. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2267. self.ui.replot_btn.triggered.connect(self.plot_all)
  2268. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2269. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2270. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2271. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2272. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2273. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2274. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2275. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2276. self.ui.delete_btn.triggered.connect(self.on_delete)
  2277. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2278. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2279. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2280. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2281. # Tools Toolbar Signals
  2282. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2283. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2284. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2285. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2286. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2287. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2288. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2289. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2290. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2291. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2292. def object2editor(self):
  2293. """
  2294. Send the current Geometry or Excellon object (if any) into the it's editor.
  2295. :return: None
  2296. """
  2297. self.report_usage("object2editor()")
  2298. edited_object = self.collection.get_active()
  2299. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2300. isinstance(edited_object, FlatCAMExcellon):
  2301. pass
  2302. else:
  2303. self.inform.emit('[WARNING_NOTCL] %s' %
  2304. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2305. return
  2306. if isinstance(edited_object, FlatCAMGeometry):
  2307. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2308. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2309. # we set the notebook to hidden
  2310. self.ui.splitter.setSizes([0, 1])
  2311. if edited_object.multigeo is True:
  2312. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2313. if len(edited_tools) > 1:
  2314. self.inform.emit('[WARNING_NOTCL] %s' %
  2315. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2316. "is not possible.\n"
  2317. "Edit only one geometry at a time."))
  2318. # determine the tool dia of the selected tool
  2319. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2320. # now find the key in the edited_object.tools that has this tooldia
  2321. multi_tool = 1
  2322. for tool in edited_object.tools:
  2323. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2324. multi_tool = tool
  2325. break
  2326. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2327. else:
  2328. self.geo_editor.edit_fcgeometry(edited_object)
  2329. # set call source to the Editor we go into
  2330. self.call_source = 'geo_editor'
  2331. elif isinstance(edited_object, FlatCAMExcellon):
  2332. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2333. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2334. if self.ui.splitter.sizes()[0] == 0:
  2335. self.ui.splitter.setSizes([1, 1])
  2336. self.exc_editor.edit_fcexcellon(edited_object)
  2337. # set call source to the Editor we go into
  2338. self.call_source = 'exc_editor'
  2339. elif isinstance(edited_object, FlatCAMGerber):
  2340. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2341. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2342. if self.ui.splitter.sizes()[0] == 0:
  2343. self.ui.splitter.setSizes([1, 1])
  2344. self.grb_editor.edit_fcgerber(edited_object)
  2345. # set call source to the Editor we go into
  2346. self.call_source = 'grb_editor'
  2347. # make sure that we can't select another object while in Editor Mode:
  2348. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2349. self.ui.project_frame.setDisabled(True)
  2350. # delete any selection shape that might be active as they are not relevant in Editor
  2351. self.delete_selection_shape()
  2352. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2353. self.ui.plot_tab_area.protectTab(0)
  2354. self.inform.emit('[WARNING_NOTCL] %s' %
  2355. _("Editor is activated ..."))
  2356. self.should_we_save = True
  2357. def editor2object(self, cleanup=None):
  2358. """
  2359. Transfers the Geometry or Excellon from it's editor to the current object.
  2360. :return: None
  2361. """
  2362. self.report_usage("editor2object()")
  2363. # do not update a geometry or excellon object unless it comes out of an editor
  2364. if self.call_source != 'app':
  2365. edited_obj = self.collection.get_active()
  2366. if cleanup is None:
  2367. msgbox = QtWidgets.QMessageBox()
  2368. msgbox.setText(_("Do you want to save the edited object?"))
  2369. msgbox.setWindowTitle(_("Close Editor"))
  2370. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2371. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2372. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2373. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2374. msgbox.setDefaultButton(bt_yes)
  2375. msgbox.exec_()
  2376. response = msgbox.clickedButton()
  2377. if response == bt_yes:
  2378. # clean the Tools Tab
  2379. self.ui.tool_scroll_area.takeWidget()
  2380. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2381. self.ui.notebook.setTabText(2, "Tool")
  2382. if isinstance(edited_obj, FlatCAMGeometry):
  2383. obj_type = "Geometry"
  2384. if cleanup is None:
  2385. self.geo_editor.update_fcgeometry(edited_obj)
  2386. self.geo_editor.update_options(edited_obj)
  2387. self.geo_editor.deactivate()
  2388. # update the geo object options so it is including the bounding box values
  2389. try:
  2390. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2391. edited_obj.options['xmin'] = xmin
  2392. edited_obj.options['ymin'] = ymin
  2393. edited_obj.options['xmax'] = xmax
  2394. edited_obj.options['ymax'] = ymax
  2395. except AttributeError as e:
  2396. self.inform.emit('[WARNING] %s' %
  2397. _("Object empty after edit."))
  2398. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2399. elif isinstance(edited_obj, FlatCAMGerber):
  2400. obj_type = "Gerber"
  2401. if cleanup is None:
  2402. self.grb_editor.update_fcgerber()
  2403. self.grb_editor.update_options(edited_obj)
  2404. self.grb_editor.deactivate_grb_editor()
  2405. # delete the old object (the source object) if it was an empty one
  2406. if len(edited_obj.solid_geometry) == 0:
  2407. old_name = edited_obj.options['name']
  2408. self.collection.set_active(old_name)
  2409. self.collection.delete_active()
  2410. elif isinstance(edited_obj, FlatCAMExcellon):
  2411. obj_type = "Excellon"
  2412. if cleanup is None:
  2413. self.exc_editor.update_fcexcellon(edited_obj)
  2414. self.exc_editor.update_options(edited_obj)
  2415. self.exc_editor.deactivate()
  2416. else:
  2417. self.inform.emit('[WARNING_NOTCL] %s' %
  2418. _("Select a Gerber, Geometry or Excellon Object to update."))
  2419. return
  2420. self.inform.emit('[selected] %s %s' %
  2421. (obj_type, _("is updated, returning to App...")))
  2422. elif response == bt_no:
  2423. # clean the Tools Tab
  2424. self.ui.tool_scroll_area.takeWidget()
  2425. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2426. self.ui.notebook.setTabText(2, "Tool")
  2427. if isinstance(edited_obj, FlatCAMGeometry):
  2428. self.geo_editor.deactivate()
  2429. elif isinstance(edited_obj, FlatCAMGerber):
  2430. self.grb_editor.deactivate_grb_editor()
  2431. elif isinstance(edited_obj, FlatCAMExcellon):
  2432. self.exc_editor.deactivate()
  2433. # set focus on the project tab
  2434. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2435. else:
  2436. self.inform.emit('[WARNING_NOTCL] %s' %
  2437. _("Select a Gerber, Geometry or Excellon Object to update."))
  2438. return
  2439. elif response == bt_cancel:
  2440. return
  2441. else:
  2442. if isinstance(edited_obj, FlatCAMGeometry):
  2443. self.geo_editor.deactivate()
  2444. elif isinstance(edited_obj, FlatCAMGerber):
  2445. self.grb_editor.deactivate_grb_editor()
  2446. elif isinstance(edited_obj, FlatCAMExcellon):
  2447. self.exc_editor.deactivate()
  2448. else:
  2449. self.inform.emit('[WARNING_NOTCL] %s' %
  2450. _("Select a Gerber, Geometry or Excellon Object to update."))
  2451. return
  2452. # if notebook is hidden we show it
  2453. if self.ui.splitter.sizes()[0] == 0:
  2454. self.ui.splitter.setSizes([1, 1])
  2455. # restore the call_source to app
  2456. self.call_source = 'app'
  2457. edited_obj.plot()
  2458. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2459. self.ui.plot_tab_area.protectTab(0)
  2460. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2461. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2462. self.ui.project_frame.setDisabled(False)
  2463. def get_last_folder(self):
  2464. """
  2465. Get the folder path from where the last file was opened.
  2466. :return: String, last opened folder path
  2467. """
  2468. return self.defaults["global_last_folder"]
  2469. def get_last_save_folder(self):
  2470. """
  2471. Get the folder path from where the last file was saved.
  2472. :return: String, last saved folder path
  2473. """
  2474. loc = self.defaults["global_last_save_folder"]
  2475. if loc is None:
  2476. loc = self.defaults["global_last_folder"]
  2477. if loc is None:
  2478. loc = os.path.dirname(__file__)
  2479. return loc
  2480. def report_usage(self, resource):
  2481. """
  2482. Increments usage counter for the given resource
  2483. in self.defaults['global_stats'].
  2484. :param resource: Name of the resource.
  2485. :return: None
  2486. """
  2487. if resource in self.defaults['global_stats']:
  2488. self.defaults['global_stats'][resource] += 1
  2489. else:
  2490. self.defaults['global_stats'][resource] = 1
  2491. def init_tcl(self):
  2492. """
  2493. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2494. :return: None
  2495. """
  2496. if hasattr(self, 'tcl'):
  2497. # self.tcl = None
  2498. # TODO we need to clean non default variables and procedures here
  2499. # new object cannot be used here as it will not remember values created for next passes,
  2500. # because tcl was execudted in old instance of TCL
  2501. pass
  2502. else:
  2503. self.tcl = tk.Tcl()
  2504. self.setup_shell()
  2505. self.log.debug("TCL Shell has been initialized.")
  2506. # TODO: This shouldn't be here.
  2507. class TclErrorException(Exception):
  2508. """
  2509. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2510. """
  2511. pass
  2512. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2513. """
  2514. Shows a message on the FlatCAM Shell
  2515. :param msg: Message to display.
  2516. :param show: Opens the shell.
  2517. :param error: Shows the message as an error.
  2518. :param warning: Shows the message as an warning.
  2519. :param success: Shows the message as an success.
  2520. :param selected: Indicate that something was selected on canvas
  2521. :return: None
  2522. """
  2523. if show:
  2524. self.ui.shell_dock.show()
  2525. try:
  2526. if error:
  2527. self.shell.append_error(msg + "\n")
  2528. elif warning:
  2529. self.shell.append_warning(msg + "\n")
  2530. elif success:
  2531. self.shell.append_success(msg + "\n")
  2532. elif selected:
  2533. self.shell.append_selected(msg + "\n")
  2534. else:
  2535. self.shell.append_output(msg + "\n")
  2536. except AttributeError:
  2537. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2538. def raise_tcl_unknown_error(self, unknownException):
  2539. """
  2540. Raise exception if is different type than TclErrorException
  2541. this is here mainly to show unknown errors inside TCL shell console.
  2542. :param unknownException:
  2543. :return:
  2544. """
  2545. if not isinstance(unknownException, self.TclErrorException):
  2546. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2547. else:
  2548. raise unknownException
  2549. def display_tcl_error(self, error, error_info=None):
  2550. """
  2551. Escape bracket [ with '\' otherwise there is error
  2552. "ERROR: missing close-bracket" instead of real error
  2553. :param error: it may be text or exception
  2554. :param error_info: Some informations about the error
  2555. :return: None
  2556. """
  2557. if isinstance(error, Exception):
  2558. exc_type, exc_value, exc_traceback = error_info
  2559. if not isinstance(error, self.TclErrorException):
  2560. show_trace = 1
  2561. else:
  2562. show_trace = int(self.defaults['global_verbose_error_level'])
  2563. if show_trace > 0:
  2564. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2565. trc_formated = []
  2566. for a in reversed(trc):
  2567. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2568. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2569. else:
  2570. text = "%s" % error
  2571. else:
  2572. text = error
  2573. text = text.replace('[', '\\[').replace('"', '\\"')
  2574. self.tcl.eval('return -code error "%s"' % text)
  2575. def raise_tcl_error(self, text):
  2576. """
  2577. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2578. :param text: text of error
  2579. :return: raise exception
  2580. """
  2581. self.display_tcl_error(text)
  2582. raise self.TclErrorException(text)
  2583. def exec_command(self, text, no_plot=None):
  2584. """
  2585. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2586. Also handles execution in separated threads
  2587. :param text: FlatCAM TclCommand with parameters
  2588. :return: output if there was any
  2589. """
  2590. self.report_usage('exec_command')
  2591. result = self.exec_command_test(text, False)
  2592. # MS: added this method call so the geometry is updated once the TCL command is executed
  2593. # if no_plot is None:
  2594. # self.plot_all()
  2595. return result
  2596. def exec_command_test(self, text, reraise=True):
  2597. """
  2598. Same as exec_command(...) with additional control over exceptions.
  2599. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2600. :param text: Input command
  2601. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2602. :return: Output from the command
  2603. """
  2604. tcl_command_string = str(text)
  2605. try:
  2606. self.shell.open_proccessing() # Disables input box.
  2607. result = self.tcl.eval(str(tcl_command_string))
  2608. if result != 'None':
  2609. self.shell.append_output(result + '\n')
  2610. except tk.TclError as e:
  2611. # This will display more precise answer if something in TCL shell fails
  2612. result = self.tcl.eval("set errorInfo")
  2613. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2614. self.shell.append_error('ERROR: ' + result + '\n')
  2615. # Show error in console and just return or in test raise exception
  2616. if reraise:
  2617. raise e
  2618. finally:
  2619. self.shell.close_proccessing()
  2620. pass
  2621. return result
  2622. # """
  2623. # Code below is unsused. Saved for later.
  2624. # """
  2625. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2626. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2627. # self.log.debug(parts)
  2628. # try:
  2629. # if parts[0] not in commands:
  2630. # self.shell.append_error("Unknown command\n")
  2631. # return
  2632. #
  2633. # #import inspect
  2634. # #inspect.getargspec(someMethod)
  2635. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2636. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2637. # self.shell.append_error(
  2638. # "Command %s takes %d arguments. %d given.\n" %
  2639. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2640. # )
  2641. # return
  2642. #
  2643. # cmdfcn = commands[parts[0]]["fcn"]
  2644. # cmdconv = commands[parts[0]]["converters"]
  2645. # if len(parts) - 1 > 0:
  2646. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2647. # else:
  2648. # retval = cmdfcn()
  2649. # retfcn = commands[parts[0]]["retfcn"]
  2650. # if retval and retfcn(retval):
  2651. # self.shell.append_output(retfcn(retval) + "\n")
  2652. #
  2653. # except Exception as e:
  2654. # #self.shell.append_error(''.join(traceback.format_exc()))
  2655. # #self.shell.append_error("?\n")
  2656. # self.shell.append_error(str(e) + "\n")
  2657. def info(self, msg):
  2658. """
  2659. Informs the user. Normally on the status bar, optionally
  2660. also on the shell.
  2661. :param msg: Text to write.
  2662. :return: None
  2663. """
  2664. # Type of message in brackets at the beginning of the message.
  2665. match = re.search("\[([^\]]+)\](.*)", msg)
  2666. if match:
  2667. level = match.group(1)
  2668. msg_ = match.group(2)
  2669. self.ui.fcinfo.set_status(str(msg_), level=level)
  2670. if level.lower() == "error":
  2671. self.shell_message(msg, error=True, show=True)
  2672. elif level.lower() == "warning":
  2673. self.shell_message(msg, warning=True, show=True)
  2674. elif level.lower() == "error_notcl":
  2675. self.shell_message(msg, error=True, show=False)
  2676. elif level.lower() == "warning_notcl":
  2677. self.shell_message(msg, warning=True, show=False)
  2678. elif level.lower() == "success":
  2679. self.shell_message(msg, success=True, show=False)
  2680. elif level.lower() == "selected":
  2681. self.shell_message(msg, selected=True, show=False)
  2682. else:
  2683. self.shell_message(msg, show=False)
  2684. else:
  2685. self.ui.fcinfo.set_status(str(msg), level="info")
  2686. # make sure that if the message is to clear the infobar with a space
  2687. # is not printed over and over on the shell
  2688. if msg != '':
  2689. self.shell_message(msg)
  2690. def restore_toolbar_view(self):
  2691. """
  2692. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2693. was saved in the defaults dictionary.
  2694. :return: None
  2695. """
  2696. tb = self.defaults["global_toolbar_view"]
  2697. if tb & 1:
  2698. self.ui.toolbarfile.setVisible(True)
  2699. else:
  2700. self.ui.toolbarfile.setVisible(False)
  2701. if tb & 2:
  2702. self.ui.toolbargeo.setVisible(True)
  2703. else:
  2704. self.ui.toolbargeo.setVisible(False)
  2705. if tb & 4:
  2706. self.ui.toolbarview.setVisible(True)
  2707. else:
  2708. self.ui.toolbarview.setVisible(False)
  2709. if tb & 8:
  2710. self.ui.toolbartools.setVisible(True)
  2711. else:
  2712. self.ui.toolbartools.setVisible(False)
  2713. if tb & 16:
  2714. self.ui.exc_edit_toolbar.setVisible(True)
  2715. else:
  2716. self.ui.exc_edit_toolbar.setVisible(False)
  2717. if tb & 32:
  2718. self.ui.geo_edit_toolbar.setVisible(True)
  2719. else:
  2720. self.ui.geo_edit_toolbar.setVisible(False)
  2721. if tb & 64:
  2722. self.ui.grb_edit_toolbar.setVisible(True)
  2723. else:
  2724. self.ui.grb_edit_toolbar.setVisible(False)
  2725. if tb & 128:
  2726. self.ui.snap_toolbar.setVisible(True)
  2727. else:
  2728. self.ui.snap_toolbar.setVisible(False)
  2729. if tb & 256:
  2730. self.ui.toolbarshell.setVisible(True)
  2731. else:
  2732. self.ui.toolbarshell.setVisible(False)
  2733. def load_defaults(self, filename):
  2734. """
  2735. Loads the aplication's default settings from current_defaults.FlatConfig into
  2736. ``self.defaults``.
  2737. :return: None
  2738. """
  2739. try:
  2740. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2741. options = f.read()
  2742. f.close()
  2743. except IOError:
  2744. self.log.error("Could not load defaults file.")
  2745. self.inform.emit('[ERROR] %s' %
  2746. _("Could not load defaults file."))
  2747. # in case the defaults file can't be loaded, show all toolbars
  2748. self.defaults["global_toolbar_view"] = 511
  2749. return
  2750. try:
  2751. defaults = json.loads(options)
  2752. except:
  2753. # in case the defaults file can't be loaded, show all toolbars
  2754. self.defaults["global_toolbar_view"] = 511
  2755. e = sys.exc_info()[0]
  2756. App.log.error(str(e))
  2757. self.inform.emit('[ERROR] %s' %
  2758. _("Failed to parse defaults file."))
  2759. return
  2760. self.defaults.update(defaults)
  2761. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2762. # restore the toolbar view
  2763. self.restore_toolbar_view()
  2764. def on_import_preferences(self):
  2765. """
  2766. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2767. ``self.defaults``.
  2768. :return: None
  2769. """
  2770. self.report_usage("on_import_preferences")
  2771. App.log.debug("on_import_preferences()")
  2772. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2773. try:
  2774. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2775. directory=self.data_path,
  2776. filter=filter_)
  2777. except TypeError:
  2778. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2779. filter=filter_)
  2780. filename = str(filename)
  2781. if filename == "":
  2782. self.inform.emit('[WARNING_NOTCL] %s' %
  2783. _("FlatCAM preferences import cancelled."))
  2784. else:
  2785. try:
  2786. f = open(filename)
  2787. options = f.read()
  2788. f.close()
  2789. except IOError:
  2790. self.log.error("Could not load defaults file.")
  2791. self.inform.emit('[ERROR_NOTCL] %s' %
  2792. _("Could not load defaults file."))
  2793. return
  2794. try:
  2795. defaults_from_file = json.loads(options)
  2796. except Exception as e:
  2797. e = sys.exc_info()[0]
  2798. App.log.error(str(e))
  2799. self.inform.emit('[ERROR_NOTCL] %s' %
  2800. _("Failed to parse defaults file."))
  2801. return
  2802. self.defaults.update(defaults_from_file)
  2803. self.on_preferences_edited()
  2804. self.inform.emit('[success] %s: %s' %
  2805. (_("Imported Defaults from"), filename))
  2806. def on_export_preferences(self):
  2807. """
  2808. Save the defaults dictionary to a file.
  2809. :return: None
  2810. """
  2811. self.report_usage("on_export_preferences")
  2812. App.log.debug("on_export_preferences()")
  2813. defaults_file_content = None
  2814. self.date = str(datetime.today()).rpartition('.')[0]
  2815. self.date = ''.join(c for c in self.date if c not in ':-')
  2816. self.date = self.date.replace(' ', '_')
  2817. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2818. try:
  2819. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2820. caption=_("Export FlatCAM Preferences"),
  2821. directory=self.data_path + '/preferences_' + self.date,
  2822. filter=filter__
  2823. )
  2824. except TypeError:
  2825. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2826. filter=filter__)
  2827. filename = str(filename)
  2828. defaults_from_file = {}
  2829. if filename == "":
  2830. self.inform.emit('[WARNING_NOTCL] %s' %
  2831. _("FlatCAM preferences export cancelled."))
  2832. return
  2833. else:
  2834. try:
  2835. f = open(filename, 'w')
  2836. defaults_file_content = f.read()
  2837. f.close()
  2838. except PermissionError:
  2839. self.inform.emit('[WARNING] %s' %
  2840. _("Permission denied, saving not possible.\n"
  2841. "Most likely another app is holding the file open and not accessible."))
  2842. return
  2843. except IOError:
  2844. App.log.debug('Creating a new preferences file ...')
  2845. f = open(filename, 'w')
  2846. json.dump({}, f)
  2847. f.close()
  2848. except:
  2849. e = sys.exc_info()[0]
  2850. App.log.error("Could not load defaults file.")
  2851. App.log.error(str(e))
  2852. self.inform.emit('[ERROR_NOTCL] %s' %
  2853. _("Could not load preferences file."))
  2854. return
  2855. try:
  2856. defaults_from_file = json.loads(defaults_file_content)
  2857. except:
  2858. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2859. # Update options
  2860. self.defaults_read_form()
  2861. defaults_from_file.update(self.defaults)
  2862. self.propagate_defaults(silent=True)
  2863. # Save update options
  2864. try:
  2865. f = open(filename, "w")
  2866. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2867. f.close()
  2868. except:
  2869. self.inform.emit('[ERROR_NOTCL] %s' %
  2870. _("Failed to write defaults to file."))
  2871. return
  2872. if self.defaults["global_open_style"] is False:
  2873. self.file_opened.emit("preferences", filename)
  2874. self.file_saved.emit("preferences", filename)
  2875. self.inform.emit('[success] %s: %s' %
  2876. (_("Exported preferences to"), filename))
  2877. def on_preferences_open_folder(self):
  2878. """
  2879. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2880. :return: None
  2881. """
  2882. self.report_usage("on_preferences_open_folder()")
  2883. if sys.platform == 'win32':
  2884. subprocess.Popen('explorer %s' % self.data_path)
  2885. elif sys.platform == 'darwin':
  2886. os.system('open "%s"' % self.data_path)
  2887. else:
  2888. subprocess.Popen(['xdg-open', self.data_path])
  2889. self.inform.emit('[success] %s' %
  2890. _("FlatCAM Preferences Folder opened."))
  2891. def save_geometry(self, x, y, width, height, notebook_width):
  2892. """
  2893. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2894. launch of the application.
  2895. :param x: X position of the main window
  2896. :param y: Y position of the main window
  2897. :param width: width of the main window
  2898. :param height: height of the main window
  2899. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2900. :return: None
  2901. """
  2902. self.defaults["global_def_win_x"] = x
  2903. self.defaults["global_def_win_y"] = y
  2904. self.defaults["global_def_win_w"] = width
  2905. self.defaults["global_def_win_h"] = height
  2906. self.defaults["global_def_notebook_width"] = notebook_width
  2907. self.save_defaults()
  2908. def message_dialog(self, title, message, kind="info"):
  2909. """
  2910. Builds and show a custom QMessageBox to be used in FlatCAM.
  2911. :param title: title of the QMessageBox
  2912. :param message: message to be displayed
  2913. :param kind: type of QMessageBox; will display a specific icon.
  2914. :return:
  2915. """
  2916. icon = {"info": QtWidgets.QMessageBox.Information,
  2917. "warning": QtWidgets.QMessageBox.Warning,
  2918. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2919. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2920. dlg.setText(message)
  2921. dlg.exec_()
  2922. def register_recent(self, kind, filename):
  2923. """
  2924. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2925. dictionary.
  2926. :param kind: type of file that was opened
  2927. :param filename: the path and file name for the file that was opened
  2928. :return:
  2929. """
  2930. self.log.debug("register_recent()")
  2931. self.log.debug(" %s" % kind)
  2932. self.log.debug(" %s" % filename)
  2933. record = {'kind': str(kind), 'filename': str(filename)}
  2934. if record in self.recent:
  2935. return
  2936. if record in self.recent_projects:
  2937. return
  2938. if record['kind'] == 'project':
  2939. self.recent_projects.insert(0, record)
  2940. else:
  2941. self.recent.insert(0, record)
  2942. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2943. self.recent.pop()
  2944. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2945. self.recent_projects.pop()
  2946. try:
  2947. f = open(self.data_path + '/recent.json', 'w')
  2948. except IOError:
  2949. App.log.error("Failed to open recent items file for writing.")
  2950. self.inform.emit('[ERROR_NOTCL] %s' %
  2951. _('Failed to open recent files file for writing.'))
  2952. return
  2953. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2954. f.close()
  2955. try:
  2956. fp = open(self.data_path + '/recent_projects.json', 'w')
  2957. except IOError:
  2958. App.log.error("Failed to open recent items file for writing.")
  2959. self.inform.emit('[ERROR_NOTCL] %s' %
  2960. _('Failed to open recent projects file for writing.'))
  2961. return
  2962. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2963. fp.close()
  2964. # Re-build the recent items menu
  2965. self.setup_recent_items()
  2966. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2967. """
  2968. Creates a new specialized FlatCAMObj and attaches it to the application,
  2969. this is, updates the GUI accordingly, any other records and plots it.
  2970. This method is thread-safe.
  2971. Notes:
  2972. * If the name is in use, the self.collection will modify it
  2973. when appending it to the collection. There is no need to handle
  2974. name conflicts here.
  2975. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2976. :type kind: str
  2977. :param name: Name for the object.
  2978. :type name: str
  2979. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2980. The function is called with 2 parameters: the new object and the App instance.
  2981. :type initialize: function
  2982. :param active:
  2983. :param fit:
  2984. :param plot: If to plot the resulting object
  2985. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2986. self.colleaction
  2987. :return: None
  2988. :rtype: None
  2989. """
  2990. App.log.debug("new_object()")
  2991. obj_plot = plot
  2992. obj_autoselected = autoselected
  2993. t0 = time.time() # Debug
  2994. # ## Create object
  2995. classdict = {
  2996. "gerber": FlatCAMGerber,
  2997. "excellon": FlatCAMExcellon,
  2998. "cncjob": FlatCAMCNCjob,
  2999. "geometry": FlatCAMGeometry
  3000. }
  3001. App.log.debug("Calling object constructor...")
  3002. obj = classdict[kind](name)
  3003. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3004. # Set options from "Project options" form
  3005. self.options_read_form()
  3006. # IMPORTANT
  3007. # The key names in defaults and options dictionary's are not random:
  3008. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3009. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3010. # the options from project options form into the self.options. After that, below, depending on the type of
  3011. # object that is created, it will strip the name of the object and the underline (if the original key was
  3012. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3013. # "toolchange"
  3014. for option in self.options:
  3015. if option.find(kind + "_") == 0:
  3016. oname = option[len(kind) + 1:]
  3017. obj.options[oname] = self.options[option]
  3018. obj.isHovering = False
  3019. obj.notHovering = True
  3020. # Initialize as per user request
  3021. # User must take care to implement initialize
  3022. # in a thread-safe way as is is likely that we
  3023. # have been invoked in a separate thread.
  3024. t1 = time.time()
  3025. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3026. try:
  3027. return_value = initialize(obj, self)
  3028. except Exception as e:
  3029. msg = '[ERROR_NOTCL] %s' % \
  3030. _("An internal error has ocurred. See shell.\n")
  3031. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3032. msg += traceback.format_exc()
  3033. self.inform.emit(msg)
  3034. # if str(e) == "Empty Geometry":
  3035. # self.inform.emit("[ERROR_NOTCL] )
  3036. # else:
  3037. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3038. return "fail"
  3039. t2 = time.time()
  3040. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3041. if return_value == 'fail':
  3042. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3043. return "fail"
  3044. # Check units and convert if necessary
  3045. # This condition CAN be true because initialize() can change obj.units
  3046. if self.options["units"].upper() != obj.units.upper():
  3047. self.inform.emit('%s: %s' %
  3048. (_("Converting units to "), self.options["units"]))
  3049. obj.convert_units(self.options["units"])
  3050. t3 = time.time()
  3051. self.log.debug("%f seconds converting units." % (t3 - t2))
  3052. # Create the bounding box for the object and then add the results to the obj.options
  3053. try:
  3054. xmin, ymin, xmax, ymax = obj.bounds()
  3055. obj.options['xmin'] = xmin
  3056. obj.options['ymin'] = ymin
  3057. obj.options['xmax'] = xmax
  3058. obj.options['ymax'] = ymax
  3059. except Exception as e:
  3060. log.warning("The object has no bounds properties. %s" % str(e))
  3061. return "fail"
  3062. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3063. # Move the object to the main thread and let the app know that it is available.
  3064. obj.moveToThread(self.main_thread)
  3065. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3066. return obj
  3067. def new_excellon_object(self):
  3068. """
  3069. Creates a new, blank Excellon object.
  3070. :return: None
  3071. """
  3072. self.report_usage("new_excellon_object()")
  3073. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3074. def new_geometry_object(self):
  3075. """
  3076. Creates a new, blank and single-tool Geometry object.
  3077. :return: None
  3078. """
  3079. self.report_usage("new_geometry_object()")
  3080. def initialize(obj, self):
  3081. obj.multitool = False
  3082. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3083. def new_gerber_object(self):
  3084. """
  3085. Creates a new, blank Gerber object.
  3086. :return: None
  3087. """
  3088. self.report_usage("new_gerber_object()")
  3089. def initialize(grb_obj, self):
  3090. grb_obj.multitool = False
  3091. grb_obj.source_file = []
  3092. grb_obj.multigeo = False
  3093. grb_obj.follow = False
  3094. grb_obj.apertures = {}
  3095. grb_obj.solid_geometry = []
  3096. try:
  3097. grb_obj.options['xmin'] = 0
  3098. grb_obj.options['ymin'] = 0
  3099. grb_obj.options['xmax'] = 0
  3100. grb_obj.options['ymax'] = 0
  3101. except KeyError:
  3102. pass
  3103. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3104. def on_object_created(self, obj, plot, autoselect):
  3105. """
  3106. Event callback for object creation.
  3107. It will add the new object to the collection. After that it will plot the object in a threaded way
  3108. :param obj: The newly created FlatCAM object.
  3109. :param plot: if the newly create object t obe plotted
  3110. :param autoselect: if the newly created object to be autoselected after creation
  3111. :return: None
  3112. """
  3113. t0 = time.time() # DEBUG
  3114. self.log.debug("on_object_created()")
  3115. # The Collection might change the name if there is a collision
  3116. self.collection.append(obj)
  3117. # after adding the object to the collection always update the list of objects that are in the collection
  3118. self.all_objects_list = self.collection.get_list()
  3119. # self.inform.emit('[selected] %s created & selected: %s' %
  3120. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3121. if obj.kind == 'gerber':
  3122. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3123. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3124. elif obj.kind == 'excellon':
  3125. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3126. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3127. elif obj.kind == 'cncjob':
  3128. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3129. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3130. elif obj.kind == 'geometry':
  3131. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3132. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3133. # update the SHELL auto-completer model with the name of the new object
  3134. self.myKeywords.append(obj.options['name'])
  3135. self.shell._edit.set_model_data(self.myKeywords)
  3136. self.ui.code_editor.set_model_data(self.myKeywords)
  3137. if autoselect:
  3138. # select the just opened object but deselect the previous ones
  3139. self.collection.set_all_inactive()
  3140. self.collection.set_active(obj.options["name"])
  3141. else:
  3142. self.collection.set_all_inactive()
  3143. # here it is done the object plotting
  3144. def worker_task(t_obj):
  3145. with self.proc_container.new(_("Plotting")):
  3146. if isinstance(t_obj, FlatCAMCNCjob):
  3147. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3148. else:
  3149. t_obj.plot()
  3150. t1 = time.time() # DEBUG
  3151. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3152. self.object_plotted.emit(t_obj)
  3153. # Send to worker
  3154. # self.worker.add_task(worker_task, [self])
  3155. if plot is True:
  3156. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3157. def on_object_changed(self, obj):
  3158. """
  3159. Called whenever the geometry of the object was changed in some way.
  3160. This require the update of it's bounding values so it can be the selected on canvas.
  3161. Update the bounding box data from obj.options
  3162. :param obj: the object that was changed
  3163. :return: None
  3164. """
  3165. xmin, ymin, xmax, ymax = obj.bounds()
  3166. obj.options['xmin'] = xmin
  3167. obj.options['ymin'] = ymin
  3168. obj.options['xmax'] = xmax
  3169. obj.options['ymax'] = ymax
  3170. log.debug("Object changed, updating the bounding box data on self.options")
  3171. # delete the old selection shape
  3172. self.delete_selection_shape()
  3173. self.should_we_save = True
  3174. def on_object_plotted(self, obj):
  3175. """
  3176. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3177. :param obj: object to be fit into view
  3178. :return: None
  3179. """
  3180. self.on_zoom_fit(None)
  3181. def options_read_form(self):
  3182. """
  3183. Same as it's equivalent from the defaults.
  3184. self.options use to store the preferences per project. No longer used.
  3185. :return: None
  3186. """
  3187. for option in self.options_form_fields:
  3188. self.options[option] = self.options_form_fields[option].get_value()
  3189. def options_write_form(self):
  3190. """
  3191. Same as it's equivalent from the defaults.
  3192. self.options use to store the preferences per project. No longer used.
  3193. :return: None
  3194. """
  3195. for option in self.options:
  3196. self.options_write_form_field(option)
  3197. def options_write_form_field(self, field):
  3198. """
  3199. Same as it's equivalent from the defaults.
  3200. self.options use to store the preferences per project. No longer used.
  3201. :return: None
  3202. """
  3203. try:
  3204. self.options_form_fields[field].set_value(self.options[field])
  3205. except KeyError:
  3206. # Changed from error to debug. This allows to have data stored
  3207. # which is not user-editable.
  3208. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3209. pass
  3210. def on_about(self):
  3211. """
  3212. Displays the "about" dialog found in the Menu --> Help.
  3213. :return: None
  3214. """
  3215. self.report_usage("on_about")
  3216. version = self.version
  3217. version_date = self.version_date
  3218. beta = self.beta
  3219. class AboutDialog(QtWidgets.QDialog):
  3220. def __init__(self, parent=None):
  3221. QtWidgets.QDialog.__init__(self, parent)
  3222. # Icon and title
  3223. self.setWindowIcon(parent.app_icon)
  3224. self.setWindowTitle(_("About FlatCAM"))
  3225. self.resize(600, 200)
  3226. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3227. # self.setStyleSheet(
  3228. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3229. # "background-attachment: fixed"
  3230. # )
  3231. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3232. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3233. # palette = QtGui.QPalette()
  3234. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3235. # self.setPalette(palette)
  3236. logo = QtWidgets.QLabel()
  3237. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3238. title = QtWidgets.QLabel(
  3239. "<font size=8><B>FlatCAM</B></font><BR>"
  3240. "{title}<BR>"
  3241. "<BR>"
  3242. "<BR>"
  3243. "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3244. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3245. "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3246. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3247. "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3248. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">here.</a><BR>".
  3249. format(title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3250. devel=_("Development"), down=_("DOWNLOAD"), issue=_("Issue tracker"))
  3251. )
  3252. title.setOpenExternalLinks(True)
  3253. closebtn = QtWidgets.QPushButton(_("Close"))
  3254. tab_widget = QtWidgets.QTabWidget()
  3255. description_label = QtWidgets.QLabel(
  3256. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3257. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3258. version=version,beta=('BETA' if beta else ''),
  3259. date=version_date,
  3260. arch=platform.architecture()[0])
  3261. )
  3262. description_label.setOpenExternalLinks(True)
  3263. license_label = QtWidgets.QLabel(
  3264. _(
  3265. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3266. 'Licensed under the MIT license:\n'
  3267. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3268. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3269. 'of this software and associated documentation files (the "Software"), to deal\n'
  3270. 'in the Software without restriction, including without limitation the rights\n'
  3271. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3272. 'copies of the Software, and to permit persons to whom the Software is\n'
  3273. ' furnished to do so, subject to the following conditions:\n\n'
  3274. 'The above copyright notice and this permission notice shall be included in\n'
  3275. 'all copies or substantial portions of the Software.\n\n'
  3276. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3277. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3278. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3279. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3280. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3281. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3282. 'THE SOFTWARE.'
  3283. )
  3284. )
  3285. license_label.setOpenExternalLinks(True)
  3286. # layouts
  3287. layout1 = QtWidgets.QVBoxLayout()
  3288. layout1_1 = QtWidgets.QHBoxLayout()
  3289. layout1_2 = QtWidgets.QHBoxLayout()
  3290. layout2 = QtWidgets.QHBoxLayout()
  3291. layout3 = QtWidgets.QHBoxLayout()
  3292. self.setLayout(layout1)
  3293. layout1.addLayout(layout1_1)
  3294. layout1.addLayout(layout1_2)
  3295. layout1.addLayout(layout2)
  3296. layout1.addLayout(layout3)
  3297. layout1_1.addStretch()
  3298. layout1_1.addWidget(description_label)
  3299. layout1_2.addWidget(tab_widget)
  3300. self.splash_tab = QtWidgets.QWidget()
  3301. self.splash_tab.setObjectName("splash_about")
  3302. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3303. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3304. tab_widget.addTab(self.splash_tab, _("Splash"))
  3305. self.programmmers_tab = QtWidgets.QWidget()
  3306. self.programmmers_tab.setObjectName("programmers_about")
  3307. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3308. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3309. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3310. self.translators_tab = QtWidgets.QWidget()
  3311. self.translators_tab.setObjectName("translators_about")
  3312. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3313. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3314. tab_widget.addTab(self.translators_tab, _("Translators"))
  3315. self.license_tab = QtWidgets.QWidget()
  3316. self.license_tab.setObjectName("license_about")
  3317. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3318. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3319. tab_widget.addTab(self.license_tab, _("License"))
  3320. self.splash_tab_layout.addWidget(logo, stretch=0)
  3321. self.splash_tab_layout.addWidget(title, stretch=1)
  3322. self.prog_grid_lay = QtWidgets.QGridLayout()
  3323. prog_widget = QtWidgets.QWidget()
  3324. prog_widget.setLayout(self.prog_grid_lay)
  3325. self.programmmers_tab_layout.addWidget(prog_widget)
  3326. self.programmmers_tab_layout.addStretch()
  3327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  3331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 1)
  3333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  3335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Maintainer >=2019")), 4, 1)
  3337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 5, 0)
  3338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 1)
  3339. self.translator_grid_lay = QtWidgets.QGridLayout()
  3340. trans_widget = QtWidgets.QWidget()
  3341. trans_widget.setLayout(self.translator_grid_lay)
  3342. self.translators_tab_layout.addWidget(trans_widget)
  3343. self.translators_tab_layout.addStretch()
  3344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3362. self.translator_grid_lay.setColumnStretch(0, 0)
  3363. # self.translators_tab_layout.addStretch()
  3364. self.license_tab_layout.addWidget(license_label)
  3365. self.license_tab_layout.addStretch()
  3366. layout3.addStretch()
  3367. layout3.addWidget(closebtn)
  3368. closebtn.clicked.connect(self.accept)
  3369. AboutDialog(self.ui).exec_()
  3370. def on_file_savedefaults(self):
  3371. """
  3372. Callback for menu item File->Save Defaults. Saves application default options
  3373. ``self.defaults`` to current_defaults.FlatConfig.
  3374. :return: None
  3375. """
  3376. self.save_defaults()
  3377. # def on_app_exit(self):
  3378. # self.report_usage("on_app_exit()")
  3379. #
  3380. # if self.collection.get_list():
  3381. # msgbox = QtWidgets.QMessageBox()
  3382. # # msgbox.setText("<B>Save changes ...</B>")
  3383. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3384. # "\n"
  3385. # "Do you want to Save the project?")
  3386. # msgbox.setWindowTitle("Save changes")
  3387. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3388. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3389. # QtWidgets.QMessageBox.Cancel)
  3390. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3391. #
  3392. # response = msgbox.exec_()
  3393. #
  3394. # if response == QtWidgets.QMessageBox.Yes:
  3395. # self.on_file_saveprojectas(thread=False)
  3396. # elif response == QtWidgets.QMessageBox.Cancel:
  3397. # return
  3398. # self.save_defaults()
  3399. # else:
  3400. # self.save_defaults()
  3401. # log.debug("Application defaults saved ... Exit event.")
  3402. # QtWidgets.qApp.quit()
  3403. def save_defaults(self, silent=False, data_path=None):
  3404. """
  3405. Saves application default options
  3406. ``self.defaults`` to current_defaults.FlatConfig file.
  3407. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3408. used at the next launch of the application.
  3409. :param silent: whether to display a message in status bar or not; boolean
  3410. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3411. When the application is portable it should be a mobile location.
  3412. :return: None
  3413. """
  3414. self.report_usage("save_defaults")
  3415. if data_path is None:
  3416. data_path = self.data_path
  3417. # Read options from file
  3418. try:
  3419. f = open(data_path + "/current_defaults.FlatConfig")
  3420. defaults_file_content = f.read()
  3421. f.close()
  3422. except:
  3423. e = sys.exc_info()[0]
  3424. App.log.error("Could not load defaults file.")
  3425. App.log.error(str(e))
  3426. self.inform.emit('[ERROR_NOTCL] %s' %
  3427. _("Could not load defaults file."))
  3428. return
  3429. try:
  3430. defaults = json.loads(defaults_file_content)
  3431. except:
  3432. e = sys.exc_info()[0]
  3433. App.log.error("Failed to parse defaults file.")
  3434. App.log.error(str(e))
  3435. self.inform.emit('[ERROR_NOTCL] %s' %
  3436. _("Failed to parse defaults file."))
  3437. return
  3438. # Update options
  3439. self.defaults_read_form()
  3440. defaults.update(self.defaults)
  3441. self.propagate_defaults(silent=True)
  3442. # Save the toolbar view
  3443. tb_status = 0
  3444. if self.ui.toolbarfile.isVisible():
  3445. tb_status += 1
  3446. if self.ui.toolbargeo.isVisible():
  3447. tb_status += 2
  3448. if self.ui.toolbarview.isVisible():
  3449. tb_status += 4
  3450. if self.ui.toolbartools.isVisible():
  3451. tb_status += 8
  3452. if self.ui.exc_edit_toolbar.isVisible():
  3453. tb_status += 16
  3454. if self.ui.geo_edit_toolbar.isVisible():
  3455. tb_status += 32
  3456. if self.ui.grb_edit_toolbar.isVisible():
  3457. tb_status += 64
  3458. if self.ui.snap_toolbar.isVisible():
  3459. tb_status += 128
  3460. if self.ui.toolbarshell.isVisible():
  3461. tb_status += 256
  3462. self.defaults["global_toolbar_view"] = tb_status
  3463. # Save update options
  3464. try:
  3465. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3466. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3467. f.close()
  3468. except:
  3469. self.inform.emit('[ERROR_NOTCL] %s' %
  3470. _("Failed to write defaults to file."))
  3471. return
  3472. if not silent:
  3473. self.inform.emit('[success] %s' %
  3474. _("Preferences saved."))
  3475. def save_factory_defaults(self, silent=False, data_path=None):
  3476. """
  3477. Saves application factory default options
  3478. ``self.defaults`` to factory_defaults.FlatConfig.
  3479. It's a one time job done just after the first install.
  3480. :param silent: whether to display a message in status bar or not; boolean
  3481. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3482. When the application is portable it should be a mobile location.
  3483. :return: None
  3484. """
  3485. self.report_usage("save_factory_defaults")
  3486. if data_path is None:
  3487. data_path = self.data_path
  3488. # Read options from file
  3489. try:
  3490. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3491. factory_defaults_file_content = f_f_def.read()
  3492. f_f_def.close()
  3493. except:
  3494. e = sys.exc_info()[0]
  3495. App.log.error("Could not load factory defaults file.")
  3496. App.log.error(str(e))
  3497. self.inform.emit('[ERROR_NOTCL] %s' %
  3498. _("Could not load factory defaults file."))
  3499. return
  3500. try:
  3501. factory_defaults = json.loads(factory_defaults_file_content)
  3502. except:
  3503. e = sys.exc_info()[0]
  3504. App.log.error("Failed to parse factory defaults file.")
  3505. App.log.error(str(e))
  3506. self.inform.emit('[ERROR_NOTCL] %s' %
  3507. _("Failed to parse factory defaults file."))
  3508. return
  3509. # Update options
  3510. self.defaults_read_form()
  3511. factory_defaults.update(self.defaults)
  3512. self.propagate_defaults(silent=True)
  3513. # Save update options
  3514. try:
  3515. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3516. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3517. f_f_def_s.close()
  3518. except:
  3519. self.inform.emit('[ERROR_NOTCL] %s' %
  3520. _("Failed to write factory defaults to file."))
  3521. return
  3522. if silent is False:
  3523. self.inform.emit(_("Factory defaults saved."))
  3524. def final_save(self):
  3525. """
  3526. Callback for doing a preferences save to file whenever the application is about to quit.
  3527. If the project has changes, it will ask the user to save the project.
  3528. :return: None
  3529. """
  3530. if self.save_in_progress:
  3531. self.inform.emit('[WARNING_NOTCL] %s' %
  3532. _("Application is saving the project. Please wait ..."))
  3533. return
  3534. if self.should_we_save and self.collection.get_list():
  3535. msgbox = QtWidgets.QMessageBox()
  3536. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3537. "\n"
  3538. "Do you want to Save the project?"))
  3539. msgbox.setWindowTitle(_("Save changes"))
  3540. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3541. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3542. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3543. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3544. msgbox.setDefaultButton(bt_yes)
  3545. msgbox.exec_()
  3546. response = msgbox.clickedButton()
  3547. if response == bt_yes:
  3548. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3549. elif response == bt_no:
  3550. self.quit_application()
  3551. elif response == bt_cancel:
  3552. return
  3553. else:
  3554. self.quit_application()
  3555. def quit_application(self):
  3556. """
  3557. Called (as a pyslot or not) when the application is quit.
  3558. :return: None
  3559. """
  3560. self.save_defaults()
  3561. log.debug("App.final_save() --> App Defaults saved.")
  3562. # save toolbar state to file
  3563. settings = QSettings("Open Source", "FlatCAM")
  3564. settings.setValue('saved_gui_state', self.ui.saveState())
  3565. settings.setValue('maximized_gui', self.ui.isMaximized())
  3566. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3567. settings.setValue('notebook_font_size',
  3568. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3569. settings.setValue('axis_font_size',
  3570. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3571. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3572. # This will write the setting to the platform specific storage.
  3573. del settings
  3574. log.debug("App.final_save() --> App UI state saved.")
  3575. QtWidgets.qApp.quit()
  3576. def on_portable_checked(self, state):
  3577. """
  3578. Callback called when the checkbox in Preferences GUI is checked.
  3579. It will set the application as portable by creating the preferences and recent files in the
  3580. 'config' folder found in the FlatCAM installation folder.
  3581. :param state: boolean, the state of the checkbox when clicked/checked
  3582. :return:
  3583. """
  3584. line_no = 0
  3585. data = None
  3586. if sys.platform != 'win32':
  3587. # this won't work in Linux or MacOS
  3588. return
  3589. # test if the app was frozen and choose the path for the configuration file
  3590. if getattr(sys, "frozen", False) is True:
  3591. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3592. else:
  3593. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3594. config_file = current_data_path + '\\configuration.txt'
  3595. try:
  3596. with open(config_file, 'r') as f:
  3597. try:
  3598. data = f.readlines()
  3599. except Exception as e:
  3600. log.debug('App.__init__() -->%s' % str(e))
  3601. return
  3602. except FileNotFoundError:
  3603. pass
  3604. for line in data:
  3605. line = line.strip('\n')
  3606. param = str(line).rpartition('=')
  3607. if param[0] == 'portable':
  3608. break
  3609. line_no += 1
  3610. if state:
  3611. data[line_no] = 'portable=True\n'
  3612. # create the new defauults files
  3613. # create current_defaults.FlatConfig file if there is none
  3614. try:
  3615. f = open(current_data_path + '/current_defaults.FlatConfig')
  3616. f.close()
  3617. except IOError:
  3618. App.log.debug('Creating empty current_defaults.FlatConfig')
  3619. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3620. json.dump({}, f)
  3621. f.close()
  3622. # create factory_defaults.FlatConfig file if there is none
  3623. try:
  3624. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3625. f.close()
  3626. except IOError:
  3627. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3628. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3629. json.dump({}, f)
  3630. f.close()
  3631. try:
  3632. f = open(current_data_path + '/recent.json')
  3633. f.close()
  3634. except IOError:
  3635. App.log.debug('Creating empty recent.json')
  3636. f = open(current_data_path + '/recent.json', 'w')
  3637. json.dump([], f)
  3638. f.close()
  3639. try:
  3640. fp = open(current_data_path + '/recent_projects.json')
  3641. fp.close()
  3642. except IOError:
  3643. App.log.debug('Creating empty recent_projects.json')
  3644. fp = open(current_data_path + '/recent_projects.json', 'w')
  3645. json.dump([], fp)
  3646. fp.close()
  3647. # save the current defaults to the new defaults file
  3648. self.save_defaults(silent=True, data_path=current_data_path)
  3649. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3650. else:
  3651. data[line_no] = 'portable=False\n'
  3652. with open(config_file, 'w') as f:
  3653. f.writelines(data)
  3654. def on_toggle_shell(self):
  3655. """
  3656. Toggle shell: if is visible close it, if it is closed then open it
  3657. :return:
  3658. """
  3659. self.report_usage("on_toggle_shell()")
  3660. if self.ui.shell_dock.isVisible():
  3661. self.ui.shell_dock.hide()
  3662. else:
  3663. self.ui.shell_dock.show()
  3664. def on_register_files(self, obj_type=None):
  3665. """
  3666. Called whenever there is a need to register file extensions with FlatCAM.
  3667. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3668. :param obj_type: the type of object to be register for.
  3669. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3670. :return: None
  3671. """
  3672. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3673. new_reg_path = 'Software\\Classes\\'
  3674. # find if the current user is admin
  3675. try:
  3676. is_admin = os.getuid() == 0
  3677. except AttributeError:
  3678. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3679. if is_admin is True:
  3680. root_path = winreg.HKEY_CLASSES_ROOT
  3681. else:
  3682. root_path = winreg.HKEY_CURRENT_USER
  3683. # create the keys
  3684. def set_reg(name, root_path, new_reg_path, value):
  3685. try:
  3686. winreg.CreateKey(root_path, new_reg_path)
  3687. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3688. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3689. return True
  3690. except WindowsError:
  3691. return False
  3692. # delete key in registry
  3693. def delete_reg(root_path, reg_path, key_to_del):
  3694. key_to_del_path = reg_path + key_to_del
  3695. try:
  3696. winreg.DeleteKey(root_path, key_to_del_path)
  3697. return True
  3698. except WindowsError:
  3699. return False
  3700. if obj_type is None or obj_type == 'excellon':
  3701. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3702. exc_list = [x for x in exc_list if x != '']
  3703. # register all keys in the Preferences window
  3704. for ext in exc_list:
  3705. new_k = new_reg_path + ext
  3706. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3707. # and unregister those that are no longer in the Preferences windows but are in the file
  3708. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3709. if ext not in exc_list:
  3710. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3711. # now write the updated extensions to the self.defaults
  3712. new_ext = ''
  3713. for ext in exc_list:
  3714. new_ext = new_ext + ext + ', '
  3715. self.defaults["fa_excellon"] = new_ext
  3716. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3717. if obj_type is None or obj_type == 'gcode':
  3718. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3719. gco_list = [x for x in gco_list if x != '']
  3720. # register all keys in the Preferences window
  3721. for ext in gco_list:
  3722. new_k = new_reg_path + ext
  3723. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3724. # and unregister those that are no longer in the Preferences windows but are in the file
  3725. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3726. if ext not in gco_list:
  3727. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3728. # now write the updated extensions to the self.defaults
  3729. new_ext = ''
  3730. for ext in gco_list:
  3731. new_ext = new_ext + ext + ', '
  3732. self.defaults["fa_gcode"] = new_ext
  3733. self.inform.emit('[success] %s' %
  3734. _("Selected GCode file extensions registered with FlatCAM."))
  3735. if obj_type is None or obj_type == 'gerber':
  3736. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3737. grb_list = [x for x in grb_list if x != '']
  3738. # register all keys in the Preferences window
  3739. for ext in grb_list:
  3740. new_k = new_reg_path + ext
  3741. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3742. # and unregister those that are no longer in the Preferences windows but are in the file
  3743. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3744. if ext not in grb_list:
  3745. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3746. # now write the updated extensions to the self.defaults
  3747. new_ext = ''
  3748. for ext in grb_list:
  3749. new_ext = new_ext + ext + ', '
  3750. self.defaults["fa_gerber"] = new_ext
  3751. self.inform.emit('[success] %s' %
  3752. _("Selected Gerber file extensions registered with FlatCAM."))
  3753. def on_edit_join(self, name=None):
  3754. """
  3755. Callback for Edit->Join. Joins the selected geometry objects into
  3756. a new one.
  3757. :return: None
  3758. """
  3759. self.report_usage("on_edit_join()")
  3760. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3761. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3762. tooldias = []
  3763. geo_type_list = set()
  3764. objs = self.collection.get_selected()
  3765. if len(objs) < 2:
  3766. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3767. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3768. return 'fail'
  3769. for obj in objs:
  3770. geo_type_list.add(obj.multigeo)
  3771. # if len(geo_type_list) == 1 means that all list elements are the same
  3772. if len(geo_type_list) != 1:
  3773. self.inform.emit('[ERROR] %s' %
  3774. _("Failed join. The Geometry objects are of different types.\n"
  3775. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3776. "convert from one to another and retry joining \n"
  3777. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3778. "the result may not be what was expected. \n"
  3779. "Check the generated GCODE."))
  3780. return
  3781. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3782. if True in geo_type_list:
  3783. def initialize(obj, app):
  3784. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3785. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3786. for v in obj.tools.values():
  3787. v['data']['name'] = obj_name_multi
  3788. self.new_object("geometry", obj_name_multi, initialize)
  3789. else:
  3790. def initialize(obj, app):
  3791. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3792. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3793. for v in obj.tools.values():
  3794. v['data']['name'] = obj_name_single
  3795. self.new_object("geometry", obj_name_single, initialize)
  3796. self.should_we_save = True
  3797. def on_edit_join_exc(self):
  3798. """
  3799. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3800. a new Excellon.
  3801. :return: None
  3802. """
  3803. self.report_usage("on_edit_join_exc()")
  3804. objs = self.collection.get_selected()
  3805. for obj in objs:
  3806. if not isinstance(obj, FlatCAMExcellon):
  3807. self.inform.emit('[ERROR_NOTCL] %s' %
  3808. _("Failed. Excellon joining works only on Excellon objects."))
  3809. return
  3810. if len(objs) < 2:
  3811. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3812. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3813. return 'fail'
  3814. def initialize(obj, app):
  3815. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3816. self.new_object("excellon", 'Combo_Excellon', initialize)
  3817. self.should_we_save = True
  3818. def on_edit_join_grb(self):
  3819. """
  3820. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3821. a new Gerber object.
  3822. :return: None
  3823. """
  3824. self.report_usage("on_edit_join_grb()")
  3825. objs = self.collection.get_selected()
  3826. for obj in objs:
  3827. if not isinstance(obj, FlatCAMGerber):
  3828. self.inform.emit('[ERROR_NOTCL] %s' %
  3829. _("Failed. Gerber joining works only on Gerber objects."))
  3830. return
  3831. if len(objs) < 2:
  3832. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3833. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3834. return 'fail'
  3835. def initialize(obj, app):
  3836. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3837. self.new_object("gerber", 'Combo_Gerber', initialize)
  3838. self.should_we_save = True
  3839. def on_convert_singlegeo_to_multigeo(self):
  3840. """
  3841. Called for converting a Geometry object from single-geo to multi-geo.
  3842. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3843. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3844. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3845. the solid-geometry of that tool.
  3846. :return: None
  3847. """
  3848. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3849. obj = self.collection.get_active()
  3850. if obj is None:
  3851. self.inform.emit('[ERROR_NOTCL] %s' %
  3852. _("Failed. Select a Geometry Object and try again."))
  3853. return
  3854. if not isinstance(obj, FlatCAMGeometry):
  3855. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3856. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3857. return
  3858. obj.multigeo = True
  3859. for tooluid, dict_value in obj.tools.items():
  3860. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3861. if not isinstance(obj.solid_geometry, list):
  3862. obj.solid_geometry = [obj.solid_geometry]
  3863. obj.solid_geometry[:] = []
  3864. obj.plot()
  3865. self.should_we_save = True
  3866. self.inform.emit('[success] %s' %
  3867. _("A Geometry object was converted to MultiGeo type."))
  3868. def on_convert_multigeo_to_singlegeo(self):
  3869. """
  3870. Called for converting a Geometry object from multi-geo to single-geo.
  3871. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3872. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3873. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3874. the solid-geometry of that tool.
  3875. :return: None
  3876. """
  3877. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3878. obj = self.collection.get_active()
  3879. if obj is None:
  3880. self.inform.emit('[ERROR_NOTCL] %s' %
  3881. _("Failed. Select a Geometry Object and try again."))
  3882. return
  3883. if not isinstance(obj, FlatCAMGeometry):
  3884. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3885. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3886. return
  3887. obj.multigeo = False
  3888. total_solid_geometry = []
  3889. for tooluid, dict_value in obj.tools.items():
  3890. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3891. # clear the original geometry
  3892. dict_value['solid_geometry'][:] = []
  3893. obj.solid_geometry = deepcopy(total_solid_geometry)
  3894. obj.plot()
  3895. self.should_we_save = True
  3896. self.inform.emit('[success] %s' %
  3897. _("A Geometry object was converted to SingleGeo type."))
  3898. def on_options_dict_change(self, field):
  3899. """
  3900. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3901. current project. This feature is no longer used.
  3902. :param field:
  3903. :return:
  3904. """
  3905. self.options_write_form_field(field)
  3906. if field == "units":
  3907. self.set_screen_units(self.options['units'])
  3908. def on_defaults_dict_change(self, field):
  3909. """
  3910. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3911. Edit -> Preferences tab window.
  3912. :param field: the key of the self.defaults dictionary that was changed.
  3913. :return: None
  3914. """
  3915. self.defaults_write_form_field(field)
  3916. if field == "units":
  3917. self.set_screen_units(self.defaults['units'])
  3918. def set_screen_units(self, units):
  3919. """
  3920. Set the FlatCAM units on the status bar.
  3921. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3922. :return: None
  3923. """
  3924. self.ui.units_label.setText("[" + units.lower() + "]")
  3925. def on_toggle_units(self, no_pref=False):
  3926. """
  3927. Callback for the Units radio-button change in the Preferences tab.
  3928. Changes the application's default units adn for the project too.
  3929. If changing the project's units, the change propagates to all of
  3930. the objects in the project.
  3931. :return: None
  3932. """
  3933. self.report_usage("on_toggle_units")
  3934. if self.toggle_units_ignore:
  3935. return
  3936. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3937. # If option is the same, then ignore
  3938. if new_units == self.defaults["units"].upper():
  3939. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3940. return
  3941. # Options to scale
  3942. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3943. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3944. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3945. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3946. "excellon_z_pdepth",
  3947. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3948. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3949. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3950. "geometry_feedrate_probe",
  3951. 'cncjob_tooldia',
  3952. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3953. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3954. "tools_2sided_drilldia", "tools_film_boundary",
  3955. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3956. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3957. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3958. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3959. "tools_transform_offset_y",
  3960. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3961. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3962. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3963. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3964. 'global_gridx', 'global_gridy', 'global_snap_max']
  3965. def scale_options(sfactor):
  3966. for dim in dimensions:
  3967. if dim == 'excellon_toolchangexy':
  3968. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3969. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3970. coords_xy[0] *= sfactor
  3971. coords_xy[1] *= sfactor
  3972. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3973. elif dim == 'geometry_toolchangexy':
  3974. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3975. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3976. coords_xy[0] *= sfactor
  3977. coords_xy[1] *= sfactor
  3978. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3979. elif dim == 'geometry_cnctooldia':
  3980. tools_diameters = []
  3981. try:
  3982. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3983. tools_diameters = [eval(a) for a in tools_string if a != '']
  3984. except Exception as e:
  3985. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3986. self.options['geometry_cnctooldia'] = ''
  3987. for t in range(len(tools_diameters)):
  3988. tools_diameters[t] *= sfactor
  3989. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3990. elif dim == 'tools_ncctools':
  3991. ncctools = []
  3992. try:
  3993. tools_string = self.defaults["tools_ncctools"].split(",")
  3994. ncctools = [eval(a) for a in tools_string if a != '']
  3995. except Exception as e:
  3996. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3997. self.options['tools_ncctools'] = ''
  3998. for t in range(len(ncctools)):
  3999. ncctools[t] *= sfactor
  4000. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4001. elif dim == 'tools_solderpaste_tools':
  4002. sptools = []
  4003. try:
  4004. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4005. sptools = [eval(a) for a in tools_string if a != '']
  4006. except Exception as e:
  4007. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4008. self.options['tools_solderpaste_tools'] = ""
  4009. for t in range(len(sptools)):
  4010. sptools[t] *= sfactor
  4011. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4012. elif dim == 'tools_solderpaste_xy_toolchange':
  4013. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4014. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4015. sp_coords[0] *= sfactor
  4016. sp_coords[1] *= sfactor
  4017. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4018. elif dim == 'global_gridx' or dim == 'global_gridy':
  4019. if new_units == 'IN':
  4020. val = 0.1
  4021. try:
  4022. val = float(self.defaults[dim]) * sfactor
  4023. except Exception as e:
  4024. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4025. self.options[dim] = float('%.6f' % val)
  4026. else:
  4027. val = 0.1
  4028. try:
  4029. val = float(self.defaults[dim]) * sfactor
  4030. except Exception as e:
  4031. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4032. self.options[dim] = float('%.4f' % val)
  4033. else:
  4034. val = 0.1
  4035. try:
  4036. val = float(self.options[dim]) * sfactor
  4037. except Exception as e:
  4038. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4039. self.options[dim] = val
  4040. def scale_defaults(sfactor):
  4041. for dim in dimensions:
  4042. if dim == 'excellon_toolchangexy':
  4043. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4044. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4045. coords_xy[0] *= sfactor
  4046. coords_xy[1] *= sfactor
  4047. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4048. elif dim == 'geometry_toolchangexy':
  4049. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4050. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4051. coords_xy[0] *= sfactor
  4052. coords_xy[1] *= sfactor
  4053. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4054. elif dim == 'geometry_cnctooldia':
  4055. tools_diameters = []
  4056. try:
  4057. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4058. tools_diameters = [eval(a) for a in tools_string if a != '']
  4059. except Exception as e:
  4060. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4061. self.defaults['geometry_cnctooldia'] = ''
  4062. for t in range(len(tools_diameters)):
  4063. tools_diameters[t] *= sfactor
  4064. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4065. elif dim == 'tools_ncctools':
  4066. ncctools = []
  4067. try:
  4068. tools_string = self.defaults["tools_ncctools"].split(",")
  4069. ncctools = [eval(a) for a in tools_string if a != '']
  4070. except Exception as e:
  4071. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4072. self.defaults['tools_ncctools'] = ''
  4073. for t in range(len(ncctools)):
  4074. ncctools[t] *= sfactor
  4075. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4076. elif dim == 'tools_solderpaste_tools':
  4077. sptools = []
  4078. try:
  4079. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4080. sptools = [eval(a) for a in tools_string if a != '']
  4081. except Exception as e:
  4082. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4083. self.defaults['tools_solderpaste_tools'] = ""
  4084. for t in range(len(sptools)):
  4085. sptools[t] *= sfactor
  4086. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4087. elif dim == 'tools_solderpaste_xy_toolchange':
  4088. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4089. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4090. sp_coords[0] *= sfactor
  4091. sp_coords[1] *= sfactor
  4092. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4093. elif dim == 'global_gridx' or dim == 'global_gridy':
  4094. if new_units == 'IN':
  4095. val = 0.1
  4096. try:
  4097. val = float(self.defaults[dim]) * sfactor
  4098. except Exception as e:
  4099. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4100. self.defaults[dim] = float('%.6f' % val)
  4101. else:
  4102. val = 0.1
  4103. try:
  4104. val = float(self.defaults[dim]) * sfactor
  4105. except Exception as e:
  4106. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4107. self.defaults[dim] = float('%.4f' % val)
  4108. else:
  4109. val = 0.1
  4110. try:
  4111. val = float(self.defaults[dim]) * sfactor
  4112. except Exception as e:
  4113. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4114. self.defaults[dim] = val
  4115. # The scaling factor depending on choice of units.
  4116. factor = 1/25.4
  4117. if new_units == 'MM':
  4118. factor = 25.4
  4119. # Changing project units. Warn user.
  4120. msgbox = QtWidgets.QMessageBox()
  4121. msgbox.setWindowTitle(_("Toggle Units"))
  4122. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4123. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4124. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4125. "properties of all objects to be scaled accordingly.\nContinue?"))
  4126. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4127. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4128. msgbox.setDefaultButton(bt_ok)
  4129. msgbox.exec_()
  4130. response = msgbox.clickedButton()
  4131. if response == bt_ok:
  4132. if no_pref is False:
  4133. self.options_read_form()
  4134. scale_options(factor)
  4135. self.options_write_form()
  4136. self.defaults_read_form()
  4137. scale_defaults(factor)
  4138. self.defaults_write_form(fl_units=new_units)
  4139. # save the defaults to file, some may assume that the conversion is enough and it's not
  4140. self.on_save_button()
  4141. self.should_we_save = True
  4142. # change this only if the workspace is active
  4143. if self.defaults['global_workspace'] is True:
  4144. self.plotcanvas.draw_workspace()
  4145. # adjust the grid values on the main toolbar
  4146. dec = 6 if new_units == 'IN'else 4
  4147. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4148. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4149. if not self.ui.grid_gap_link_cb.isChecked():
  4150. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4151. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4152. for obj in self.collection.get_list():
  4153. obj.convert_units(new_units)
  4154. # make that the properties stored in the object are also updated
  4155. self.object_changed.emit(obj)
  4156. obj.build_ui()
  4157. current = self.collection.get_active()
  4158. if current is not None:
  4159. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4160. if not isinstance(current, FlatCAMGeometry):
  4161. current.to_form()
  4162. self.plot_all()
  4163. self.inform.emit('[success] %s: %s' %
  4164. (_("Converted units to"), new_units))
  4165. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4166. self.set_screen_units(new_units)
  4167. else:
  4168. # Undo toggling
  4169. self.toggle_units_ignore = True
  4170. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4171. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4172. else:
  4173. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4174. self.toggle_units_ignore = False
  4175. self.inform.emit('[WARNING_NOTCL]%s' %
  4176. _(" Units conversion cancelled."))
  4177. self.options_read_form()
  4178. self.defaults_read_form()
  4179. def on_toggle_units_click(self):
  4180. try:
  4181. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4182. except (TypeError, AttributeError):
  4183. pass
  4184. if self.defaults["units"] == 'MM':
  4185. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4186. else:
  4187. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4188. self.on_toggle_units(no_pref=True)
  4189. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4190. lambda: self.on_toggle_units(no_pref=False))
  4191. def on_fullscreen(self):
  4192. self.report_usage("on_fullscreen()")
  4193. if self.toggle_fscreen is False:
  4194. if sys.platform == 'win32':
  4195. self.ui.showFullScreen()
  4196. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4197. tb.setVisible(False)
  4198. self.ui.splitter_left.setVisible(False)
  4199. self.toggle_fscreen = True
  4200. else:
  4201. if sys.platform == 'win32':
  4202. self.ui.showNormal()
  4203. self.restore_toolbar_view()
  4204. self.ui.splitter_left.setVisible(True)
  4205. self.toggle_fscreen = False
  4206. def on_toggle_plotarea(self):
  4207. self.report_usage("on_toggle_plotarea()")
  4208. try:
  4209. name = self.ui.plot_tab_area.widget(0).objectName()
  4210. except AttributeError:
  4211. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4212. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4213. self.ui.plot_tab_area.protectTab(0)
  4214. return
  4215. if name != 'plotarea':
  4216. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4217. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4218. self.ui.plot_tab_area.protectTab(0)
  4219. else:
  4220. self.ui.plot_tab_area.closeTab(0)
  4221. def on_toggle_notebook(self):
  4222. if self.ui.splitter.sizes()[0] == 0:
  4223. self.ui.splitter.setSizes([1, 1])
  4224. else:
  4225. self.ui.splitter.setSizes([0, 1])
  4226. def on_toggle_axis(self):
  4227. self.report_usage("on_toggle_axis()")
  4228. if self.toggle_axis is False:
  4229. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4230. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4231. self.plotcanvas.redraw()
  4232. self.toggle_axis = True
  4233. else:
  4234. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4235. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4236. self.plotcanvas.redraw()
  4237. self.toggle_axis = False
  4238. def on_toggle_grid(self):
  4239. self.report_usage("on_toggle_grid()")
  4240. self.ui.grid_snap_btn.trigger()
  4241. def on_options_combo_change(self, sel):
  4242. """
  4243. Called when the combo box to choose between application defaults and
  4244. project option changes value. The corresponding variables are
  4245. copied to the UI.
  4246. :param sel: The option index that was chosen.
  4247. :return: None
  4248. """
  4249. # combo_sel = self.ui.notebook.combo_options.get_active()
  4250. App.log.debug("Options --> %s" % sel)
  4251. # form = [self.defaults_form, self.options_form][sel]
  4252. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4253. if sel == 0:
  4254. self.gen_form = self.ui.general_defaults_form
  4255. self.ger_form = self.ui.gerber_defaults_form
  4256. self.exc_form = self.ui.excellon_defaults_form
  4257. self.geo_form = self.ui.geometry_defaults_form
  4258. self.cnc_form = self.ui.cncjob_defaults_form
  4259. self.tools_form = self.ui.tools_defaults_form
  4260. self.fa_form = self.ui.fa_defaults_form
  4261. elif sel == 1:
  4262. self.gen_form = self.ui.general_options_form
  4263. self.ger_form = self.ui.gerber_options_form
  4264. self.exc_form = self.ui.excellon_options_form
  4265. self.geo_form = self.ui.geometry_options_form
  4266. self.cnc_form = self.ui.cncjob_options_form
  4267. self.tools_form = self.ui.tools_options_form
  4268. self.fa_form = self.ui.fa_options_form
  4269. else:
  4270. return
  4271. try:
  4272. self.ui.general_scroll_area.takeWidget()
  4273. except:
  4274. self.log.debug("Nothing to remove")
  4275. self.ui.general_scroll_area.setWidget(self.gen_form)
  4276. self.gen_form.show()
  4277. try:
  4278. self.ui.gerber_scroll_area.takeWidget()
  4279. except:
  4280. self.log.debug("Nothing to remove")
  4281. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4282. self.ger_form.show()
  4283. try:
  4284. self.ui.excellon_scroll_area.takeWidget()
  4285. except:
  4286. self.log.debug("Nothing to remove")
  4287. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4288. self.exc_form.show()
  4289. try:
  4290. self.ui.geometry_scroll_area.takeWidget()
  4291. except:
  4292. self.log.debug("Nothing to remove")
  4293. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4294. self.geo_form.show()
  4295. try:
  4296. self.ui.cncjob_scroll_area.takeWidget()
  4297. except:
  4298. self.log.debug("Nothing to remove")
  4299. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4300. self.cnc_form.show()
  4301. try:
  4302. self.ui.tools_scroll_area.takeWidget()
  4303. except:
  4304. self.log.debug("Nothing to remove")
  4305. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4306. self.tools_form.show()
  4307. try:
  4308. self.ui.fa_scroll_area.takeWidget()
  4309. except:
  4310. self.log.debug("Nothing to remove")
  4311. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4312. self.fa_form.show()
  4313. self.log.debug("Finished GUI form initialization.")
  4314. # self.options2form()
  4315. def on_excellon_defaults_button(self):
  4316. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4317. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4318. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4319. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4320. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4321. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4322. log.debug("Excellon app defaults loaded ...")
  4323. def on_excellon_options_button(self):
  4324. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4325. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4326. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4327. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4328. self.options_form_fields["excellon_zeros"].set_value('L')
  4329. self.options_form_fields["excellon_units"].set_value('INCH')
  4330. log.debug("Excellon options defaults loaded ...")
  4331. def on_update_exc_export(self, state):
  4332. """
  4333. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4334. if the update_excellon_cb checkbox is checked
  4335. :param state: state of the checkbox whose signals is tied to his slot
  4336. :return:
  4337. """
  4338. if state:
  4339. # first try to disconnect
  4340. try:
  4341. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4342. disconnect(self.on_excellon_format_changed)
  4343. except TypeError:
  4344. pass
  4345. try:
  4346. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4347. disconnect(self.on_excellon_format_changed)
  4348. except TypeError:
  4349. pass
  4350. try:
  4351. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4352. disconnect(self.on_excellon_format_changed)
  4353. except TypeError:
  4354. pass
  4355. try:
  4356. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4357. disconnect(self.on_excellon_format_changed)
  4358. except TypeError:
  4359. pass
  4360. try:
  4361. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4362. disconnect(self.on_excellon_zeros_changed)
  4363. except TypeError:
  4364. pass
  4365. try:
  4366. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4367. disconnect(self.on_excellon_zeros_changed)
  4368. except TypeError:
  4369. pass
  4370. # the connect them
  4371. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4372. self.on_excellon_format_changed)
  4373. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4374. self.on_excellon_format_changed)
  4375. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4376. self.on_excellon_format_changed)
  4377. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4378. self.on_excellon_format_changed)
  4379. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4380. self.on_excellon_zeros_changed)
  4381. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4382. self.on_excellon_units_changed)
  4383. else:
  4384. # disconnect the signals
  4385. try:
  4386. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4387. disconnect(self.on_excellon_format_changed)
  4388. except TypeError:
  4389. pass
  4390. try:
  4391. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4392. disconnect(self.on_excellon_format_changed)
  4393. except TypeError:
  4394. pass
  4395. try:
  4396. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4397. disconnect(self.on_excellon_format_changed)
  4398. except TypeError:
  4399. pass
  4400. try:
  4401. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4402. disconnect(self.on_excellon_format_changed)
  4403. except TypeError:
  4404. pass
  4405. try:
  4406. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4407. disconnect(self.on_excellon_zeros_changed)
  4408. except TypeError:
  4409. pass
  4410. try:
  4411. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4412. disconnect(self.on_excellon_zeros_changed)
  4413. except TypeError:
  4414. pass
  4415. def on_excellon_format_changed(self):
  4416. """
  4417. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4418. :return: None
  4419. """
  4420. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4421. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4422. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4423. )
  4424. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4425. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4426. )
  4427. else:
  4428. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4429. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4430. )
  4431. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4432. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4433. )
  4434. def on_excellon_zeros_changed(self):
  4435. """
  4436. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4437. :return: None
  4438. """
  4439. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4440. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4441. )
  4442. def on_excellon_units_changed(self):
  4443. """
  4444. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4445. :return: None
  4446. """
  4447. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4449. )
  4450. self.on_excellon_format_changed()
  4451. # Setting plot colors handlers
  4452. def on_pf_color_entry(self):
  4453. self.defaults['global_plot_fill'] = \
  4454. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4455. self.defaults['global_plot_fill'][7:9]
  4456. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4457. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4458. def on_pf_color_button(self):
  4459. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4460. c_dialog = QtWidgets.QColorDialog()
  4461. plot_fill_color = c_dialog.getColor(initial=current_color)
  4462. if plot_fill_color.isValid() is False:
  4463. return
  4464. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4465. "background-color:%s" % str(plot_fill_color.name()))
  4466. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4467. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4468. self.defaults['global_plot_fill'] = new_val
  4469. def on_pf_color_spinner(self):
  4470. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4471. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4472. self.defaults['global_plot_fill'] = \
  4473. self.defaults['global_plot_fill'][:7] + \
  4474. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4475. self.defaults['global_plot_line'] = \
  4476. self.defaults['global_plot_line'][:7] + \
  4477. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4478. def on_pf_color_slider(self):
  4479. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4480. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4481. def on_pl_color_entry(self):
  4482. self.defaults['global_plot_line'] = \
  4483. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4484. self.defaults['global_plot_line'][7:9]
  4485. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4486. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4487. def on_pl_color_button(self):
  4488. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4489. # print(current_color)
  4490. c_dialog = QtWidgets.QColorDialog()
  4491. plot_line_color = c_dialog.getColor(initial=current_color)
  4492. if plot_line_color.isValid() is False:
  4493. return
  4494. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4495. "background-color:%s" % str(plot_line_color.name()))
  4496. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4497. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4498. self.defaults['global_plot_line'] = new_val_line
  4499. # Setting selection colors (left - right) handlers
  4500. def on_sf_color_entry(self):
  4501. self.defaults['global_sel_fill'] = \
  4502. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4503. self.defaults['global_sel_fill'][7:9]
  4504. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4505. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4506. def on_sf_color_button(self):
  4507. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4508. c_dialog = QtWidgets.QColorDialog()
  4509. plot_fill_color = c_dialog.getColor(initial=current_color)
  4510. if plot_fill_color.isValid() is False:
  4511. return
  4512. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4513. "background-color:%s" % str(plot_fill_color.name()))
  4514. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4515. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4516. self.defaults['global_sel_fill'] = new_val
  4517. def on_sf_color_spinner(self):
  4518. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4519. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4520. self.defaults['global_sel_fill'] = \
  4521. self.defaults['global_sel_fill'][:7] + \
  4522. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4523. self.defaults['global_sel_line'] = \
  4524. self.defaults['global_sel_line'][:7] + \
  4525. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4526. def on_sf_color_slider(self):
  4527. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4528. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4529. def on_sl_color_entry(self):
  4530. self.defaults['global_sel_line'] = \
  4531. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4532. self.defaults['global_sel_line'][7:9]
  4533. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4534. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4535. def on_sl_color_button(self):
  4536. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4537. c_dialog = QtWidgets.QColorDialog()
  4538. plot_line_color = c_dialog.getColor(initial=current_color)
  4539. if plot_line_color.isValid() is False:
  4540. return
  4541. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4542. "background-color:%s" % str(plot_line_color.name()))
  4543. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4544. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4545. self.defaults['global_sel_line'] = new_val_line
  4546. # Setting selection colors (right - left) handlers
  4547. def on_alt_sf_color_entry(self):
  4548. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4549. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4550. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4551. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4552. def on_alt_sf_color_button(self):
  4553. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4554. c_dialog = QtWidgets.QColorDialog()
  4555. plot_fill_color = c_dialog.getColor(initial=current_color)
  4556. if plot_fill_color.isValid() is False:
  4557. return
  4558. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4559. "background-color:%s" % str(plot_fill_color.name()))
  4560. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4561. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4562. self.defaults['global_alt_sel_fill'] = new_val
  4563. def on_alt_sf_color_spinner(self):
  4564. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4565. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4566. self.defaults['global_alt_sel_fill'] = \
  4567. self.defaults['global_alt_sel_fill'][:7] + \
  4568. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4569. self.defaults['global_alt_sel_line'] = \
  4570. self.defaults['global_alt_sel_line'][:7] + \
  4571. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4572. def on_alt_sf_color_slider(self):
  4573. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4574. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4575. def on_alt_sl_color_entry(self):
  4576. self.defaults['global_alt_sel_line'] = \
  4577. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4578. self.defaults['global_alt_sel_line'][7:9]
  4579. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4580. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4581. def on_alt_sl_color_button(self):
  4582. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4583. c_dialog = QtWidgets.QColorDialog()
  4584. plot_line_color = c_dialog.getColor(initial=current_color)
  4585. if plot_line_color.isValid() is False:
  4586. return
  4587. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4588. "background-color:%s" % str(plot_line_color.name()))
  4589. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4590. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4591. self.defaults['global_alt_sel_line'] = new_val_line
  4592. # Setting Editor colors
  4593. def on_draw_color_entry(self):
  4594. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4595. .draw_color_entry.get_value()
  4596. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4597. "background-color:%s" % str(self.defaults['global_draw_color']))
  4598. def on_draw_color_button(self):
  4599. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4600. c_dialog = QtWidgets.QColorDialog()
  4601. draw_color = c_dialog.getColor(initial=current_color)
  4602. if draw_color.isValid() is False:
  4603. return
  4604. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4605. "background-color:%s" % str(draw_color.name()))
  4606. new_val = str(draw_color.name())
  4607. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4608. self.defaults['global_draw_color'] = new_val
  4609. def on_sel_draw_color_entry(self):
  4610. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4611. .sel_draw_color_entry.get_value()
  4612. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4613. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4614. def on_sel_draw_color_button(self):
  4615. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4616. c_dialog = QtWidgets.QColorDialog()
  4617. sel_draw_color = c_dialog.getColor(initial=current_color)
  4618. if sel_draw_color.isValid() is False:
  4619. return
  4620. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4621. "background-color:%s" % str(sel_draw_color.name()))
  4622. new_val_sel = str(sel_draw_color.name())
  4623. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4624. self.defaults['global_sel_draw_color'] = new_val_sel
  4625. def on_proj_color_entry(self):
  4626. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4627. .proj_color_entry.get_value()
  4628. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4629. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4630. def on_proj_color_button(self):
  4631. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4632. c_dialog = QtWidgets.QColorDialog()
  4633. proj_color = c_dialog.getColor(initial=current_color)
  4634. if proj_color.isValid() is False:
  4635. return
  4636. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4637. "background-color:%s" % str(proj_color.name()))
  4638. new_val_sel = str(proj_color.name())
  4639. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4640. self.defaults['global_proj_item_color'] = new_val_sel
  4641. def on_proj_color_dis_entry(self):
  4642. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4643. .proj_color_dis_entry.get_value()
  4644. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4645. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4646. def on_proj_color_dis_button(self):
  4647. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4648. c_dialog = QtWidgets.QColorDialog()
  4649. proj_color = c_dialog.getColor(initial=current_color)
  4650. if proj_color.isValid() is False:
  4651. return
  4652. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4653. "background-color:%s" % str(proj_color.name()))
  4654. new_val_sel = str(proj_color.name())
  4655. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4656. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4657. def on_annotation_fontcolor_entry(self):
  4658. self.defaults['cncjob_annotation_fontcolor'] = \
  4659. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4660. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4661. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4662. def on_annotation_fontcolor_button(self):
  4663. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4664. c_dialog = QtWidgets.QColorDialog()
  4665. annotation_color = c_dialog.getColor(initial=current_color)
  4666. if annotation_color.isValid() is False:
  4667. return
  4668. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4669. "background-color:%s" % str(annotation_color.name()))
  4670. new_val_sel = str(annotation_color.name())
  4671. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4672. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4673. def on_splash_changed(self, state):
  4674. settings = QSettings("Open Source", "FlatCAM")
  4675. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  4676. # This will write the setting to the platform specific storage.
  4677. del settings
  4678. def on_notebook_tab_rmb_click(self, checked):
  4679. self.ui.notebook.set_detachable(val=checked)
  4680. self.defaults["global_tabs_detachable"] = checked
  4681. self.ui.plot_tab_area.set_detachable(val=checked)
  4682. self.defaults["global_tabs_detachable"] = checked
  4683. def on_deselect_all(self):
  4684. self.collection.set_all_inactive()
  4685. self.delete_selection_shape()
  4686. def on_workspace_modified(self):
  4687. self.save_defaults(silent=True)
  4688. self.plotcanvas.draw_workspace()
  4689. def on_workspace(self):
  4690. self.report_usage("on_workspace()")
  4691. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4692. self.plotcanvas.restore_workspace()
  4693. else:
  4694. self.plotcanvas.delete_workspace()
  4695. self.save_defaults(silent=True)
  4696. def on_workspace_menu(self):
  4697. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4698. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4699. else:
  4700. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4701. self.on_workspace()
  4702. def on_layout(self, index=None, lay=None):
  4703. self.report_usage("on_layout()")
  4704. if lay:
  4705. current_layout = lay
  4706. else:
  4707. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4708. settings = QSettings("Open Source", "FlatCAM")
  4709. settings.setValue('layout', current_layout)
  4710. # This will write the setting to the platform specific storage.
  4711. del settings
  4712. # first remove the toolbars:
  4713. try:
  4714. self.ui.removeToolBar(self.ui.toolbarfile)
  4715. self.ui.removeToolBar(self.ui.toolbargeo)
  4716. self.ui.removeToolBar(self.ui.toolbarview)
  4717. self.ui.removeToolBar(self.ui.toolbarshell)
  4718. self.ui.removeToolBar(self.ui.toolbartools)
  4719. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4720. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4721. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4722. self.ui.removeToolBar(self.ui.snap_toolbar)
  4723. self.ui.removeToolBar(self.ui.toolbarshell)
  4724. except Exception as e:
  4725. pass
  4726. if current_layout == 'standard':
  4727. # ## TOOLBAR INSTALLATION # ##
  4728. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4729. self.ui.toolbarfile.setObjectName('File_TB')
  4730. self.ui.addToolBar(self.ui.toolbarfile)
  4731. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4732. self.ui.toolbargeo.setObjectName('Edit_TB')
  4733. self.ui.addToolBar(self.ui.toolbargeo)
  4734. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4735. self.ui.toolbarview.setObjectName('View_TB')
  4736. self.ui.addToolBar(self.ui.toolbarview)
  4737. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4738. self.ui.toolbarshell.setObjectName('Shell_TB')
  4739. self.ui.addToolBar(self.ui.toolbarshell)
  4740. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4741. self.ui.toolbartools.setObjectName('Tools_TB')
  4742. self.ui.addToolBar(self.ui.toolbartools)
  4743. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4744. # self.ui.exc_edit_toolbar.setVisible(False)
  4745. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4746. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4747. self.ui.addToolBarBreak()
  4748. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4749. # self.ui.geo_edit_toolbar.setVisible(False)
  4750. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4751. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4752. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4753. # self.ui.grb_edit_toolbar.setVisible(False)
  4754. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4755. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4756. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4757. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4758. # self.ui.snap_toolbar.setMaximumHeight(30)
  4759. self.ui.addToolBar(self.ui.snap_toolbar)
  4760. self.ui.corner_snap_btn.setVisible(False)
  4761. self.ui.snap_magnet.setVisible(False)
  4762. elif current_layout == 'compact':
  4763. # ## TOOLBAR INSTALLATION # ##
  4764. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4765. self.ui.toolbarfile.setObjectName('File_TB')
  4766. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4767. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4768. self.ui.toolbargeo.setObjectName('Edit_TB')
  4769. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4770. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4771. self.ui.toolbarshell.setObjectName('Shell_TB')
  4772. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4773. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4774. self.ui.toolbartools.setObjectName('Tools_TB')
  4775. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4776. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4777. # self.ui.geo_edit_toolbar.setVisible(False)
  4778. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4779. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4780. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4781. self.ui.toolbarview.setObjectName('View_TB')
  4782. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  4783. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  4784. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4785. # self.ui.grb_edit_toolbar.setVisible(False)
  4786. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4787. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4788. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4789. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4790. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4791. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4792. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4793. self.ui.snap_toolbar.setMaximumHeight(30)
  4794. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4795. self.ui.corner_snap_btn.setVisible(True)
  4796. self.ui.snap_magnet.setVisible(True)
  4797. # add all the actions to the toolbars
  4798. self.ui.populate_toolbars()
  4799. # reconnect all the signals to the toolbar actions
  4800. self.connect_toolbar_signals()
  4801. self.ui.grid_snap_btn.setChecked(True)
  4802. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4803. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4804. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4805. self.ui.grid_gap_link_cb.setChecked(True)
  4806. def on_cnc_custom_parameters(self, signal_text):
  4807. if signal_text == 'Parameters':
  4808. return
  4809. else:
  4810. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4811. def on_save_button(self):
  4812. log.debug("App.on_save_button() --> Saving preferences to file.")
  4813. self.preferences_changed_flag = False
  4814. self.save_defaults(silent=False)
  4815. # load the defaults so they are updated into the app
  4816. self.load_defaults(filename='current_defaults')
  4817. # Re-fresh project options
  4818. self.on_options_app2project()
  4819. # save the notebook font size
  4820. settings = QSettings("Open Source", "FlatCAM")
  4821. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4822. settings.setValue('notebook_font_size', fsize)
  4823. # save the axis font size
  4824. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4825. settings.setValue('axis_font_size', g_fsize)
  4826. # This will write the setting to the platform specific storage.
  4827. del settings
  4828. def handlePrint(self):
  4829. self.report_usage("handlePrint()")
  4830. dialog = QtPrintSupport.QPrintDialog()
  4831. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4832. self.ui.code_editor.document().print_(dialog.printer())
  4833. def handlePreview(self):
  4834. self.report_usage("handlePreview()")
  4835. dialog = QtPrintSupport.QPrintPreviewDialog()
  4836. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4837. dialog.exec_()
  4838. def handleTextChanged(self):
  4839. # enable = not self.ui.code_editor.document().isEmpty()
  4840. # self.ui.buttonPrint.setEnabled(enable)
  4841. # self.ui.buttonPreview.setEnabled(enable)
  4842. pass
  4843. def handleOpen(self, filt=None):
  4844. self.report_usage("handleOpen()")
  4845. if filt:
  4846. _filter_ = filt
  4847. else:
  4848. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4849. "All Files (*.*)"
  4850. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4851. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4852. if path:
  4853. file = QtCore.QFile(path)
  4854. if file.open(QtCore.QIODevice.ReadOnly):
  4855. stream = QtCore.QTextStream(file)
  4856. self.gcode_edited = stream.readAll()
  4857. self.ui.code_editor.setPlainText(self.gcode_edited)
  4858. file.close()
  4859. def handleSaveGCode(self, name=None, filt=None):
  4860. self.report_usage("handleSaveGCode()")
  4861. if filt:
  4862. _filter_ = filt
  4863. else:
  4864. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4865. "All Files (*.*)"
  4866. if name:
  4867. obj_name = name
  4868. else:
  4869. try:
  4870. obj_name = self.collection.get_active().options['name']
  4871. except AttributeError:
  4872. obj_name = 'file'
  4873. if filt is None:
  4874. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4875. try:
  4876. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4877. caption=_("Export G-Code ..."),
  4878. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4879. filter=_filter_
  4880. )[0])
  4881. except TypeError:
  4882. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4883. if filename == "":
  4884. self.inform.emit('[WARNING_NOTCL] %s' %
  4885. _("Export Code cancelled."))
  4886. return
  4887. else:
  4888. try:
  4889. my_gcode = self.ui.code_editor.toPlainText()
  4890. with open(filename, 'w') as f:
  4891. for line in my_gcode:
  4892. f.write(line)
  4893. except FileNotFoundError:
  4894. self.inform.emit('[WARNING] %s' %
  4895. _("No such file or directory"))
  4896. return
  4897. except PermissionError:
  4898. self.inform.emit('[WARNING] %s' %
  4899. _("Permission denied, saving not possible.\n"
  4900. "Most likely another app is holding the file open and not accessible."))
  4901. return
  4902. # Just for adding it to the recent files list.
  4903. if self.defaults["global_open_style"] is False:
  4904. self.file_opened.emit("cncjob", filename)
  4905. self.file_saved.emit("cncjob", filename)
  4906. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  4907. def handleFindGCode(self):
  4908. self.report_usage("handleFindGCode()")
  4909. flags = QtGui.QTextDocument.FindCaseSensitively
  4910. text_to_be_found = self.ui.entryFind.get_value()
  4911. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4912. if r is False:
  4913. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4914. def handleReplaceGCode(self):
  4915. self.report_usage("handleReplaceGCode()")
  4916. old = self.ui.entryFind.get_value()
  4917. new = self.ui.entryReplace.get_value()
  4918. if self.ui.sel_all_cb.isChecked():
  4919. while True:
  4920. cursor = self.ui.code_editor.textCursor()
  4921. cursor.beginEditBlock()
  4922. flags = QtGui.QTextDocument.FindCaseSensitively
  4923. # self.ui.editor is the QPlainTextEdit
  4924. r = self.ui.code_editor.find(str(old), flags)
  4925. if r:
  4926. qc = self.ui.code_editor.textCursor()
  4927. if qc.hasSelection():
  4928. qc.insertText(new)
  4929. else:
  4930. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4931. break
  4932. # Mark end of undo block
  4933. cursor.endEditBlock()
  4934. else:
  4935. cursor = self.ui.code_editor.textCursor()
  4936. cursor.beginEditBlock()
  4937. qc = self.ui.code_editor.textCursor()
  4938. if qc.hasSelection():
  4939. qc.insertText(new)
  4940. # Mark end of undo block
  4941. cursor.endEditBlock()
  4942. def handleRunCode(self):
  4943. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  4944. # tries to print on a hidden widget, therefore show the dock if hidden
  4945. if self.ui.shell_dock.isHidden():
  4946. self.ui.shell_dock.show()
  4947. script_code = self.ui.code_editor.toPlainText()
  4948. # self.shell._sysShell.exec_command(script_code)
  4949. old_line = ''
  4950. for tcl_command_line in script_code.splitlines():
  4951. # do not process lines starting with '#' = comment and empty lines
  4952. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  4953. # id FlatCAM is run in Windows then replace all the slashes with
  4954. # the UNIX style slash that TCL understands
  4955. if sys.platform == 'win32':
  4956. if "open" in tcl_command_line:
  4957. tcl_command_line = tcl_command_line.replace('\\', '/')
  4958. if old_line != '':
  4959. new_command = old_line + tcl_command_line + '\n'
  4960. else:
  4961. new_command = tcl_command_line
  4962. # execute the actual Tcl command
  4963. try:
  4964. self.shell.open_proccessing() # Disables input box.
  4965. result = self.tcl.eval(str(new_command))
  4966. if result != 'None':
  4967. self.shell.append_output(result + '\n')
  4968. old_line = ''
  4969. except tk.TclError as e:
  4970. log.debug("App.handleRunCode() --> %s" % str(e))
  4971. old_line = old_line + tcl_command_line + '\n'
  4972. except Exception as e:
  4973. log.debug("App.handleRunCode() --> %s" % str(e))
  4974. if old_line != '':
  4975. # it means that the script finished with an error
  4976. result = self.tcl.eval("set errorInfo")
  4977. self.log.error("Exec command Exception: %s" % (result + '\n'))
  4978. self.shell.append_error('ERROR: ' + result + '\n')
  4979. self.shell.close_proccessing()
  4980. def on_tool_add_keypress(self):
  4981. # ## Current application units in Upper Case
  4982. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4983. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4984. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4985. if notebook_widget_name == 'selected_tab':
  4986. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4987. # Tool add works for Geometry only if Advanced is True in Preferences
  4988. if self.defaults["global_app_level"] == 'a':
  4989. tool_add_popup = FCInputDialog(title="New Tool ...",
  4990. text='Enter a Tool Diameter:',
  4991. min=0.0000, max=99.9999, decimals=4)
  4992. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4993. val, ok = tool_add_popup.get_value()
  4994. if ok:
  4995. if float(val) == 0:
  4996. self.inform.emit('[WARNING_NOTCL] %s' %
  4997. _("Please enter a tool diameter with non-zero value, in Float format."))
  4998. return
  4999. self.collection.get_active().on_tool_add(dia=float(val))
  5000. else:
  5001. self.inform.emit('[WARNING_NOTCL] %s...' %
  5002. _("Adding Tool cancelled"))
  5003. else:
  5004. msgbox = QtWidgets.QMessageBox()
  5005. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5006. "Go to Preferences -> General - Show Advanced Options."))
  5007. msgbox.setWindowTitle("Tool adding ...")
  5008. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5009. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5010. msgbox.setDefaultButton(bt_ok)
  5011. msgbox.exec_()
  5012. # work only if the notebook tab on focus is the Tools_Tab
  5013. if notebook_widget_name == 'tool_tab':
  5014. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5015. tool_add_popup = FCInputDialog(title="New Tool ...",
  5016. text='Enter a Tool Diameter:',
  5017. min=0.0000, max=99.9999, decimals=4)
  5018. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5019. val, ok = tool_add_popup.get_value()
  5020. # and only if the tool is NCC Tool
  5021. if tool_widget == self.ncclear_tool.toolName:
  5022. if ok:
  5023. if float(val) == 0:
  5024. self.inform.emit('[WARNING_NOTCL] %s' %
  5025. _("Please enter a tool diameter with non-zero value, in Float format."))
  5026. return
  5027. self.ncclear_tool.on_tool_add(dia=float(val))
  5028. else:
  5029. self.inform.emit('[WARNING_NOTCL] %s...' %
  5030. _("Adding Tool cancelled"))
  5031. # and only if the tool is Paint Area Tool
  5032. elif tool_widget == self.paint_tool.toolName:
  5033. if ok:
  5034. if float(val) == 0:
  5035. self.inform.emit('[WARNING_NOTCL] %s' %
  5036. _("Please enter a tool diameter with non-zero value, in Float format."))
  5037. return
  5038. self.paint_tool.on_tool_add(dia=float(val))
  5039. else:
  5040. self.inform.emit('[WARNING_NOTCL] %s...' %
  5041. _("Adding Tool cancelled"))
  5042. # and only if the tool is Solder Paste Dispensing Tool
  5043. elif tool_widget == self.paste_tool.toolName:
  5044. if ok:
  5045. if float(val) == 0:
  5046. self.inform.emit('[WARNING_NOTCL] %s' %
  5047. _("Please enter a tool diameter with non-zero value, in Float format."))
  5048. return
  5049. self.paste_tool.on_tool_add(dia=float(val))
  5050. else:
  5051. self.inform.emit('[WARNING_NOTCL] %s...' %
  5052. _("Adding Tool cancelled"))
  5053. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5054. # See description bellow.
  5055. def on_delete_keypress(self):
  5056. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5057. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5058. if notebook_widget_name == 'selected_tab':
  5059. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5060. self.collection.get_active().on_tool_delete()
  5061. # work only if the notebook tab on focus is the Tools_Tab
  5062. elif notebook_widget_name == 'tool_tab':
  5063. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5064. # and only if the tool is NCC Tool
  5065. if tool_widget == self.ncclear_tool.toolName:
  5066. self.ncclear_tool.on_tool_delete()
  5067. # and only if the tool is Paint Tool
  5068. elif tool_widget == self.paint_tool.toolName:
  5069. self.paint_tool.on_tool_delete()
  5070. # and only if the tool is Solder Paste Dispensing Tool
  5071. elif tool_widget == self.paste_tool.toolName:
  5072. self.paste_tool.on_tool_delete()
  5073. else:
  5074. self.on_delete()
  5075. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5076. # some screens you have to be careful where you hover with your mouse.
  5077. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5078. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5079. # Complicated, I know :)
  5080. def on_delete(self):
  5081. """
  5082. Delete the currently selected FlatCAMObjs.
  5083. :return: None
  5084. """
  5085. self.report_usage("on_delete()")
  5086. response = None
  5087. bt_ok = None
  5088. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5089. # a geometry object before we update it.
  5090. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5091. and self.grb_editor.editor_active is False:
  5092. if self.defaults["global_delete_confirmation"] is True:
  5093. msgbox = QtWidgets.QMessageBox()
  5094. msgbox.setWindowTitle(_("Delete objects"))
  5095. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5096. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5097. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5098. "the selected objects?"))
  5099. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5100. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5101. msgbox.setDefaultButton(bt_ok)
  5102. msgbox.exec_()
  5103. response = msgbox.clickedButton()
  5104. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5105. if self.collection.get_active():
  5106. self.log.debug("App.on_delete()")
  5107. while self.collection.get_active():
  5108. obj_active = self.collection.get_active()
  5109. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5110. if isinstance(obj_active, FlatCAMGerber):
  5111. for el in obj_active.mark_shapes:
  5112. obj_active.mark_shapes[el].clear(update=True)
  5113. obj_active.mark_shapes[el].enabled = False
  5114. # obj_active.mark_shapes[el] = None
  5115. del el
  5116. elif isinstance(obj_active, FlatCAMCNCjob):
  5117. try:
  5118. obj_active.annotation.clear(update=True)
  5119. obj_active.annotation.enabled = False
  5120. except AttributeError:
  5121. pass
  5122. self.delete_first_selected()
  5123. self.inform.emit('%s...' %
  5124. _("Object(s) deleted"))
  5125. # make sure that the selection shape is deleted, too
  5126. self.delete_selection_shape()
  5127. else:
  5128. self.inform.emit(_("Failed. No object(s) selected..."))
  5129. else:
  5130. self.inform.emit(_("Save the work in Editor and try again ..."))
  5131. def delete_first_selected(self):
  5132. # Keep this for later
  5133. try:
  5134. sel_obj = self.collection.get_active()
  5135. name = sel_obj.options["name"]
  5136. except AttributeError:
  5137. self.log.debug("Nothing selected for deletion")
  5138. return
  5139. # Remove from dictionary
  5140. self.collection.delete_active()
  5141. # Clear form
  5142. self.setup_component_editor()
  5143. self.inform.emit('%s: %s' %
  5144. (_("Object deleted"), name))
  5145. def on_set_origin(self):
  5146. """
  5147. Set the origin to the left mouse click position
  5148. :return: None
  5149. """
  5150. # display the message for the user
  5151. # and ask him to click on the desired position
  5152. self.report_usage("on_set_origin()")
  5153. def origin_replot():
  5154. def worker_task():
  5155. with self.proc_container.new('%s...' % _("Plotting")):
  5156. for obj in self.collection.get_list():
  5157. obj.plot()
  5158. self.plotcanvas.fit_view()
  5159. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5160. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5161. self.inform.emit(_('Click to set the origin ...'))
  5162. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5163. # first disconnect it as it may have been used by something else
  5164. try:
  5165. self.replot_signal.disconnect()
  5166. except TypeError:
  5167. pass
  5168. self.replot_signal[list].connect(origin_replot)
  5169. def on_set_zero_click(self, event):
  5170. # this function will be available only for mouse left click
  5171. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5172. if event.button == 1:
  5173. if self.grid_status() == True:
  5174. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5175. else:
  5176. pos = pos_canvas
  5177. x = 0 - pos[0]
  5178. y = 0 - pos[1]
  5179. def worker_task():
  5180. with self.proc_container.new(_("Setting Origin...")):
  5181. for obj in self.collection.get_list():
  5182. obj.offset((x, y))
  5183. self.object_changed.emit(obj)
  5184. # Update the object bounding box options
  5185. a, b, c, d = obj.bounds()
  5186. obj.options['xmin'] = a
  5187. obj.options['ymin'] = b
  5188. obj.options['xmax'] = c
  5189. obj.options['ymax'] = d
  5190. self.inform.emit('[success]%s...' %
  5191. _('Origin set'))
  5192. self.replot_signal.emit([])
  5193. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5194. self.should_we_save = True
  5195. def on_jump_to(self, custom_location=None, fit_center=True):
  5196. """
  5197. Jump to a location by setting the mouse cursor location
  5198. :return:
  5199. """
  5200. self.report_usage("on_jump_to()")
  5201. if not custom_location:
  5202. dia_box = Dialog_box(title=_("Jump to ..."),
  5203. label=_("Enter the coordinates in format X,Y:"),
  5204. icon=QtGui.QIcon('share/jump_to16.png'))
  5205. if dia_box.ok is True:
  5206. try:
  5207. location = eval(dia_box.location)
  5208. if not isinstance(location, tuple):
  5209. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5210. return
  5211. except:
  5212. return
  5213. else:
  5214. return
  5215. else:
  5216. location = custom_location
  5217. if fit_center:
  5218. self.plotcanvas.fit_center(loc=location)
  5219. cursor = QtGui.QCursor()
  5220. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5221. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5222. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5223. self.inform.emit('[success] %s' %
  5224. _("Done."))
  5225. return location
  5226. def on_copy_object(self):
  5227. self.report_usage("on_copy_object()")
  5228. def initialize(obj_init, app):
  5229. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5230. try:
  5231. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5232. except AttributeError:
  5233. pass
  5234. try:
  5235. obj_init.apertures = deepcopy(obj.apertures)
  5236. except AttributeError:
  5237. pass
  5238. try:
  5239. if obj.tools:
  5240. obj_init.tools = deepcopy(obj.tools)
  5241. except Exception as e:
  5242. log.debug("App.on_copy_object() --> %s" % str(e))
  5243. def initialize_excellon(obj_init, app):
  5244. obj_init.tools = deepcopy(obj.tools)
  5245. # drills are offset, so they need to be deep copied
  5246. obj_init.drills = deepcopy(obj.drills)
  5247. # slots are offset, so they need to be deep copied
  5248. obj_init.slots = deepcopy(obj.slots)
  5249. obj_init.create_geometry()
  5250. for obj in self.collection.get_selected():
  5251. obj_name = obj.options["name"]
  5252. try:
  5253. if isinstance(obj, FlatCAMExcellon):
  5254. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5255. elif isinstance(obj, FlatCAMGerber):
  5256. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5257. elif isinstance(obj, FlatCAMGeometry):
  5258. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5259. except Exception as e:
  5260. return "Operation failed: %s" % str(e)
  5261. def on_copy_object2(self, custom_name):
  5262. def initialize_geometry(obj_init, app):
  5263. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5264. try:
  5265. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5266. except AttributeError:
  5267. pass
  5268. try:
  5269. obj_init.apertures = deepcopy(obj.apertures)
  5270. except AttributeError:
  5271. pass
  5272. try:
  5273. if obj.tools:
  5274. obj_init.tools = deepcopy(obj.tools)
  5275. except Exception as e:
  5276. log.debug("on_copy_object2() --> %s" % str(e))
  5277. def initialize_gerber(obj_init, app):
  5278. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5279. obj_init.apertures = deepcopy(obj.apertures)
  5280. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5281. def initialize_excellon(obj_init, app):
  5282. obj_init.tools = deepcopy(obj.tools)
  5283. # drills are offset, so they need to be deep copied
  5284. obj_init.drills = deepcopy(obj.drills)
  5285. # slots are offset, so they need to be deep copied
  5286. obj_init.slots = deepcopy(obj.slots)
  5287. obj_init.create_geometry()
  5288. for obj in self.collection.get_selected():
  5289. obj_name = obj.options["name"]
  5290. try:
  5291. if isinstance(obj, FlatCAMExcellon):
  5292. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5293. elif isinstance(obj, FlatCAMGerber):
  5294. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5295. elif isinstance(obj, FlatCAMGeometry):
  5296. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5297. except Exception as e:
  5298. return "Operation failed: %s" % str(e)
  5299. def on_rename_object(self, text):
  5300. self.report_usage("on_rename_object()")
  5301. named_obj = self.collection.get_active()
  5302. for obj in named_obj:
  5303. if obj is list:
  5304. self.on_rename_object(text)
  5305. else:
  5306. try:
  5307. obj.options['name'] = text
  5308. except Exception as e:
  5309. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5310. def convert_any2geo(self):
  5311. self.report_usage("convert_any2geo()")
  5312. def initialize(obj_init, app):
  5313. obj_init.solid_geometry = obj.solid_geometry
  5314. try:
  5315. obj_init.follow_geometry = obj.follow_geometry
  5316. except AttributeError:
  5317. pass
  5318. try:
  5319. obj_init.apertures = obj.apertures
  5320. except AttributeError:
  5321. pass
  5322. try:
  5323. if obj.tools:
  5324. obj_init.tools = obj.tools
  5325. except AttributeError:
  5326. pass
  5327. def initialize_excellon(obj_init, app):
  5328. # objs = self.collection.get_selected()
  5329. # FlatCAMGeometry.merge(objs, obj)
  5330. solid_geo = []
  5331. for tool in obj.tools:
  5332. for geo in obj.tools[tool]['solid_geometry']:
  5333. solid_geo.append(geo)
  5334. obj_init.solid_geometry = deepcopy(solid_geo)
  5335. if not self.collection.get_selected():
  5336. log.warning("App.convert_any2geo --> No object selected")
  5337. self.inform.emit('[WARNING_NOTCL] %s' %
  5338. _("No object is selected. Select an object and try again."))
  5339. return
  5340. for obj in self.collection.get_selected():
  5341. obj_name = obj.options["name"]
  5342. try:
  5343. if isinstance(obj, FlatCAMExcellon):
  5344. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5345. else:
  5346. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5347. except Exception as e:
  5348. return "Operation failed: %s" % str(e)
  5349. def convert_any2gerber(self):
  5350. self.report_usage("convert_any2gerber()")
  5351. def initialize_geometry(obj_init, app):
  5352. apertures = {}
  5353. apid = 0
  5354. apertures[str(apid)] = {}
  5355. apertures[str(apid)]['geometry'] = []
  5356. for obj_orig in obj.solid_geometry:
  5357. new_elem = dict()
  5358. new_elem['solid'] = obj_orig
  5359. new_elem['follow'] = obj_orig.exterior
  5360. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5361. apertures[str(apid)]['size'] = 0.0
  5362. apertures[str(apid)]['type'] = 'C'
  5363. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5364. obj_init.apertures = deepcopy(apertures)
  5365. def initialize_excellon(obj_init, app):
  5366. apertures = {}
  5367. apid = 10
  5368. for tool in obj.tools:
  5369. apertures[str(apid)] = {}
  5370. apertures[str(apid)]['geometry'] = []
  5371. for geo in obj.tools[tool]['solid_geometry']:
  5372. new_el = dict()
  5373. new_el['solid'] = geo
  5374. new_el['follow'] = geo.exterior
  5375. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5376. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5377. apertures[str(apid)]['type'] = 'C'
  5378. apid += 1
  5379. # create solid_geometry
  5380. solid_geometry = []
  5381. for apid in apertures:
  5382. for geo_el in apertures[apid]['geometry']:
  5383. solid_geometry.append(geo_el['solid'])
  5384. solid_geometry = MultiPolygon(solid_geometry)
  5385. solid_geometry = solid_geometry.buffer(0.0000001)
  5386. obj_init.solid_geometry = deepcopy(solid_geometry)
  5387. obj_init.apertures = deepcopy(apertures)
  5388. # clear the working objects (perhaps not necessary due of Python GC)
  5389. apertures.clear()
  5390. if not self.collection.get_selected():
  5391. log.warning("App.convert_any2gerber --> No object selected")
  5392. self.inform.emit('[WARNING_NOTCL] %s' %
  5393. _("No object is selected. Select an object and try again."))
  5394. return
  5395. for obj in self.collection.get_selected():
  5396. obj_name = obj.options["name"]
  5397. try:
  5398. if isinstance(obj, FlatCAMExcellon):
  5399. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5400. elif isinstance(obj, FlatCAMGeometry):
  5401. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5402. else:
  5403. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5404. except Exception as e:
  5405. return "Operation failed: %s" % str(e)
  5406. def abort_all_tasks(self):
  5407. if self.abort_flag is False:
  5408. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5409. self.abort_flag = True
  5410. def app_is_idle(self):
  5411. if self.abort_flag:
  5412. self.inform.emit('[WARNING_NOTCL] %s' %
  5413. _("The current task was gracefully closed on user request..."))
  5414. self.abort_flag = False
  5415. def on_selectall(self):
  5416. self.report_usage("on_selectall()")
  5417. # delete the possible selection box around a possible selected object
  5418. self.delete_selection_shape()
  5419. for name in self.collection.get_names():
  5420. self.collection.set_active(name)
  5421. curr_sel_obj = self.collection.get_by_name(name)
  5422. # create the selection box around the selected object
  5423. if self.defaults['global_selection_shape'] is True:
  5424. self.draw_selection_shape(curr_sel_obj)
  5425. def on_preferences(self):
  5426. # add the tab if it was closed
  5427. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5428. # delete the absolute and relative position and messages in the infobar
  5429. self.ui.position_label.setText("")
  5430. self.ui.rel_position_label.setText("")
  5431. # Switch plot_area to preferences page
  5432. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5433. # self.ui.show()
  5434. # this disconnect() is done so the slot will be connected only once
  5435. try:
  5436. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5437. except (TypeError, AttributeError):
  5438. pass
  5439. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5440. # detect changes in the preferences
  5441. for idx in range(self.ui.pref_tab_area.count()):
  5442. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5443. try:
  5444. try:
  5445. tb.textEdited.disconnect(self.on_preferences_edited)
  5446. except (TypeError, AttributeError):
  5447. pass
  5448. tb.textEdited.connect(self.on_preferences_edited)
  5449. except AttributeError:
  5450. pass
  5451. try:
  5452. try:
  5453. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5454. except (TypeError, AttributeError):
  5455. pass
  5456. tb.modificationChanged.connect(self.on_preferences_edited)
  5457. except AttributeError:
  5458. pass
  5459. try:
  5460. try:
  5461. tb.toggled.disconnect(self.on_preferences_edited)
  5462. except (TypeError, AttributeError):
  5463. pass
  5464. tb.toggled.connect(self.on_preferences_edited)
  5465. except AttributeError:
  5466. pass
  5467. try:
  5468. try:
  5469. tb.valueChanged.disconnect(self.on_preferences_edited)
  5470. except (TypeError, AttributeError):
  5471. pass
  5472. tb.valueChanged.connect(self.on_preferences_edited)
  5473. except AttributeError:
  5474. pass
  5475. try:
  5476. try:
  5477. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5478. except (TypeError, AttributeError):
  5479. pass
  5480. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5481. except AttributeError:
  5482. pass
  5483. def on_preferences_edited(self):
  5484. self.inform.emit('[WARNING_NOTCL] %s' %
  5485. _("Preferences edited but not saved."))
  5486. self.preferences_changed_flag = True
  5487. def on_preferences_closed(self):
  5488. # disconnect
  5489. for idx in range(self.ui.pref_tab_area.count()):
  5490. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5491. try:
  5492. tb.textEdited.disconnect(self.on_preferences_edited)
  5493. except (TypeError, AttributeError):
  5494. pass
  5495. try:
  5496. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5497. except (TypeError, AttributeError):
  5498. pass
  5499. try:
  5500. tb.toggled.disconnect(self.on_preferences_edited)
  5501. except (TypeError, AttributeError):
  5502. pass
  5503. try:
  5504. tb.valueChanged.disconnect(self.on_preferences_edited)
  5505. except (TypeError, AttributeError):
  5506. pass
  5507. try:
  5508. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5509. except (TypeError, AttributeError):
  5510. pass
  5511. if self.preferences_changed_flag is True:
  5512. msgbox = QtWidgets.QMessageBox()
  5513. msgbox.setText(_("One or more values are changed.\n"
  5514. "Do you want to save the Preferences?"))
  5515. msgbox.setWindowTitle(_("Save Preferences"))
  5516. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5517. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5518. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5519. msgbox.setDefaultButton(bt_yes)
  5520. msgbox.exec_()
  5521. response = msgbox.clickedButton()
  5522. if response == bt_yes:
  5523. self.on_save_button()
  5524. self.inform.emit('[success] %s' %
  5525. _("Preferences saved."))
  5526. else:
  5527. self.preferences_changed_flag = False
  5528. return
  5529. def on_flipy(self):
  5530. self.report_usage("on_flipy()")
  5531. obj_list = self.collection.get_selected()
  5532. xminlist = []
  5533. yminlist = []
  5534. xmaxlist = []
  5535. ymaxlist = []
  5536. if not obj_list:
  5537. self.inform.emit('[WARNING_NOTCL] %s' %
  5538. _("No object selected to Flip on Y axis."))
  5539. else:
  5540. try:
  5541. # first get a bounding box to fit all
  5542. for obj in obj_list:
  5543. xmin, ymin, xmax, ymax = obj.bounds()
  5544. xminlist.append(xmin)
  5545. yminlist.append(ymin)
  5546. xmaxlist.append(xmax)
  5547. ymaxlist.append(ymax)
  5548. # get the minimum x,y and maximum x,y for all objects selected
  5549. xminimal = min(xminlist)
  5550. yminimal = min(yminlist)
  5551. xmaximal = max(xmaxlist)
  5552. ymaximal = max(ymaxlist)
  5553. px = 0.5 * (xminimal + xmaximal)
  5554. py = 0.5 * (yminimal + ymaximal)
  5555. # execute mirroring
  5556. for obj in obj_list:
  5557. obj.mirror('X', [px, py])
  5558. obj.plot()
  5559. self.object_changed.emit(obj)
  5560. self.inform.emit('[success] %s' %
  5561. _("Flip on Y axis done."))
  5562. except Exception as e:
  5563. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5564. (_("Flip action was not executed."), str(e)))
  5565. return
  5566. def on_flipx(self):
  5567. self.report_usage("on_flipx()")
  5568. obj_list = self.collection.get_selected()
  5569. xminlist = []
  5570. yminlist = []
  5571. xmaxlist = []
  5572. ymaxlist = []
  5573. if not obj_list:
  5574. self.inform.emit('[WARNING_NOTCL] %s' %
  5575. _("No object selected to Flip on X axis."))
  5576. else:
  5577. try:
  5578. # first get a bounding box to fit all
  5579. for obj in obj_list:
  5580. xmin, ymin, xmax, ymax = obj.bounds()
  5581. xminlist.append(xmin)
  5582. yminlist.append(ymin)
  5583. xmaxlist.append(xmax)
  5584. ymaxlist.append(ymax)
  5585. # get the minimum x,y and maximum x,y for all objects selected
  5586. xminimal = min(xminlist)
  5587. yminimal = min(yminlist)
  5588. xmaximal = max(xmaxlist)
  5589. ymaximal = max(ymaxlist)
  5590. px = 0.5 * (xminimal + xmaximal)
  5591. py = 0.5 * (yminimal + ymaximal)
  5592. # execute mirroring
  5593. for obj in obj_list:
  5594. obj.mirror('Y', [px, py])
  5595. obj.plot()
  5596. self.object_changed.emit(obj)
  5597. self.inform.emit('[success] %s' %
  5598. _("Flip on X axis done."))
  5599. except Exception as e:
  5600. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5601. (_("Flip action was not executed."), str(e)))
  5602. return
  5603. def on_rotate(self, silent=False, preset=None):
  5604. self.report_usage("on_rotate()")
  5605. obj_list = self.collection.get_selected()
  5606. xminlist = []
  5607. yminlist = []
  5608. xmaxlist = []
  5609. ymaxlist = []
  5610. if not obj_list:
  5611. self.inform.emit('[WARNING_NOTCL] %s' %
  5612. _("No object selected to Rotate."))
  5613. else:
  5614. if silent is False:
  5615. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5616. min=-360, max=360, decimals=4,
  5617. init_val=float(self.defaults['tools_transform_rotate']))
  5618. num, ok = rotatebox.get_value()
  5619. else:
  5620. num = preset
  5621. ok = True
  5622. if ok:
  5623. try:
  5624. # first get a bounding box to fit all
  5625. for obj in obj_list:
  5626. xmin, ymin, xmax, ymax = obj.bounds()
  5627. xminlist.append(xmin)
  5628. yminlist.append(ymin)
  5629. xmaxlist.append(xmax)
  5630. ymaxlist.append(ymax)
  5631. # get the minimum x,y and maximum x,y for all objects selected
  5632. xminimal = min(xminlist)
  5633. yminimal = min(yminlist)
  5634. xmaximal = max(xmaxlist)
  5635. ymaximal = max(ymaxlist)
  5636. px = 0.5 * (xminimal + xmaximal)
  5637. py = 0.5 * (yminimal + ymaximal)
  5638. for sel_obj in obj_list:
  5639. sel_obj.rotate(-float(num), point=(px, py))
  5640. sel_obj.plot()
  5641. self.object_changed.emit(sel_obj)
  5642. self.inform.emit('[success] %s' %
  5643. _("Rotation done."))
  5644. except Exception as e:
  5645. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5646. (_("Rotation movement was not executed."), str(e)))
  5647. return
  5648. def on_skewx(self):
  5649. self.report_usage("on_skewx()")
  5650. obj_list = self.collection.get_selected()
  5651. xminlist = []
  5652. yminlist = []
  5653. if not obj_list:
  5654. self.inform.emit('[WARNING_NOTCL] %s' %
  5655. _("No object selected to Skew/Shear on X axis."))
  5656. else:
  5657. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5658. min=-360, max=360, decimals=4,
  5659. init_val=float(self.defaults['tools_transform_skew_x']))
  5660. num, ok = skewxbox.get_value()
  5661. if ok:
  5662. # first get a bounding box to fit all
  5663. for obj in obj_list:
  5664. xmin, ymin, xmax, ymax = obj.bounds()
  5665. xminlist.append(xmin)
  5666. yminlist.append(ymin)
  5667. # get the minimum x,y and maximum x,y for all objects selected
  5668. xminimal = min(xminlist)
  5669. yminimal = min(yminlist)
  5670. for obj in obj_list:
  5671. obj.skew(num, 0, point=(xminimal, yminimal))
  5672. obj.plot()
  5673. self.object_changed.emit(obj)
  5674. self.inform.emit('[success] %s' %
  5675. _("Skew on X axis done."))
  5676. def on_skewy(self):
  5677. self.report_usage("on_skewy()")
  5678. obj_list = self.collection.get_selected()
  5679. xminlist = []
  5680. yminlist = []
  5681. if not obj_list:
  5682. self.inform.emit('[WARNING_NOTCL] %s' %
  5683. _("No object selected to Skew/Shear on Y axis."))
  5684. else:
  5685. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5686. min=-360, max=360, decimals=4,
  5687. init_val=float(self.defaults['tools_transform_skew_y']))
  5688. num, ok = skewybox.get_value()
  5689. if ok:
  5690. # first get a bounding box to fit all
  5691. for obj in obj_list:
  5692. xmin, ymin, xmax, ymax = obj.bounds()
  5693. xminlist.append(xmin)
  5694. yminlist.append(ymin)
  5695. # get the minimum x,y and maximum x,y for all objects selected
  5696. xminimal = min(xminlist)
  5697. yminimal = min(yminlist)
  5698. for obj in obj_list:
  5699. obj.skew(0, num, point=(xminimal, yminimal))
  5700. obj.plot()
  5701. self.object_changed.emit(obj)
  5702. self.inform.emit('[success] %s' %
  5703. _("Skew on Y axis done."))
  5704. def on_plots_updated(self):
  5705. """
  5706. Callback used to report when the plots have changed.
  5707. Adjust axes and zooms to fit.
  5708. :return: None
  5709. """
  5710. self.plotcanvas.update() # TODO: Need update canvas?
  5711. self.on_zoom_fit(None)
  5712. self.collection.update_view()
  5713. # self.inform.emit(_("Plots updated ..."))
  5714. # TODO: Rework toolbar 'clear', 'replot' functions
  5715. def on_toolbar_replot(self):
  5716. """
  5717. Callback for toolbar button. Re-plots all objects.
  5718. :return: None
  5719. """
  5720. self.report_usage("on_toolbar_replot")
  5721. self.log.debug("on_toolbar_replot()")
  5722. try:
  5723. self.collection.get_active().read_form()
  5724. except AttributeError:
  5725. self.log.debug("on_toolbar_replot(): AttributeError")
  5726. pass
  5727. self.plot_all()
  5728. def on_row_activated(self, index):
  5729. if index.isValid():
  5730. if index.internalPointer().parent_item != self.collection.root_item:
  5731. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5732. self.collection.on_item_activated(index)
  5733. def grid_status(self):
  5734. if self.ui.grid_snap_btn.isChecked():
  5735. return True
  5736. else:
  5737. return False
  5738. def populate_cmenu_grids(self):
  5739. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5740. self.ui.cmenu_gridmenu.clear()
  5741. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5742. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5743. grid_toggle.setCheckable(True)
  5744. if self.grid_status() == True:
  5745. grid_toggle.setChecked(True)
  5746. else:
  5747. grid_toggle.setChecked(False)
  5748. self.ui.cmenu_gridmenu.addSeparator()
  5749. for grid in sorted_list:
  5750. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5751. action.triggered.connect(self.set_grid)
  5752. self.ui.cmenu_gridmenu.addSeparator()
  5753. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5754. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5755. grid_add.triggered.connect(self.on_grid_add)
  5756. grid_delete.triggered.connect(self.on_grid_delete)
  5757. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5758. def set_grid(self):
  5759. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5760. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5761. def on_grid_add(self):
  5762. # ## Current application units in lower Case
  5763. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5764. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5765. text=_('Enter a Grid Value:'),
  5766. min=0.0000, max=99.9999, decimals=4)
  5767. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5768. val, ok = grid_add_popup.get_value()
  5769. if ok:
  5770. if float(val) == 0:
  5771. self.inform.emit('[WARNING_NOTCL] %s' %
  5772. _("Please enter a grid value with non-zero value, in Float format."))
  5773. return
  5774. else:
  5775. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5776. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5777. self.inform.emit('[success] %s...' %
  5778. _("New Grid added"))
  5779. else:
  5780. self.inform.emit('[WARNING_NOTCL] %s...' %
  5781. _("Grid already exists"))
  5782. else:
  5783. self.inform.emit('[WARNING_NOTCL] %s...' %
  5784. _("Adding New Grid cancelled"))
  5785. def on_grid_delete(self):
  5786. # ## Current application units in lower Case
  5787. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5788. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5789. text='Enter a Grid Value:',
  5790. min=0.0000, max=99.9999, decimals=4)
  5791. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5792. val, ok = grid_del_popup.get_value()
  5793. if ok:
  5794. if float(val) == 0:
  5795. self.inform.emit('[WARNING_NOTCL] %s' %
  5796. _("Please enter a grid value with non-zero value, in Float format."))
  5797. return
  5798. else:
  5799. try:
  5800. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5801. except ValueError:
  5802. self.inform.emit('[ERROR_NOTCL]%s...' %
  5803. _(" Grid Value does not exist"))
  5804. return
  5805. self.inform.emit('[success] %s...' %
  5806. _("Grid Value deleted"))
  5807. else:
  5808. self.inform.emit('[WARNING_NOTCL] %s...' %
  5809. _("Delete Grid value cancelled"))
  5810. def on_shortcut_list(self):
  5811. self.report_usage("on_shortcut_list()")
  5812. # add the tab if it was closed
  5813. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5814. # delete the absolute and relative position and messages in the infobar
  5815. self.ui.position_label.setText("")
  5816. self.ui.rel_position_label.setText("")
  5817. # Switch plot_area to preferences page
  5818. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5819. # self.ui.show()
  5820. def on_select_tab(self, name):
  5821. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5822. if self.ui.splitter.sizes()[0] == 0:
  5823. self.ui.splitter.setSizes([1, 1])
  5824. else:
  5825. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5826. self.ui.splitter.setSizes([0, 1])
  5827. if name == 'project':
  5828. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5829. elif name == 'selected':
  5830. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5831. elif name == 'tool':
  5832. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5833. def on_copy_name(self):
  5834. self.report_usage("on_copy_name()")
  5835. obj = self.collection.get_active()
  5836. try:
  5837. name = obj.options["name"]
  5838. except AttributeError:
  5839. log.debug("on_copy_name() --> No object selected to copy it's name")
  5840. self.inform.emit('[WARNING_NOTCL]%s' %
  5841. _(" No object selected to copy it's name"))
  5842. return
  5843. self.clipboard.setText(name)
  5844. self.inform.emit(_("Name copied on clipboard ..."))
  5845. def on_mouse_click_over_plot(self, event):
  5846. """
  5847. Default actions are:
  5848. :param event: Contains information about the event, like which button
  5849. was clicked, the pixel coordinates and the axes coordinates.
  5850. :return: None
  5851. """
  5852. self.pos = []
  5853. # So it can receive key presses
  5854. self.plotcanvas.native.setFocus()
  5855. # Set the mouse button for panning
  5856. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5857. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5858. if self.grid_status() == True:
  5859. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5860. self.app_cursor.enabled = True
  5861. else:
  5862. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5863. self.app_cursor.enabled = False
  5864. try:
  5865. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5866. if event.button == 1:
  5867. # Reset here the relative coordinates so there is a new reference on the click position
  5868. if self.rel_point1 is None:
  5869. self.rel_point1 = self.pos
  5870. else:
  5871. self.rel_point2 = copy(self.rel_point1)
  5872. self.rel_point1 = self.pos
  5873. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5874. if modifiers == QtCore.Qt.ShiftModifier:
  5875. # do not auto open the Project Tab
  5876. self.click_noproject = True
  5877. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5878. self.inform.emit('[success] %s' %
  5879. _("Coordinates copied to clipboard."))
  5880. return
  5881. self.on_mouse_move_over_plot(event, origin_click=True)
  5882. except Exception as e:
  5883. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5884. def on_double_click_over_plot(self, event):
  5885. self.doubleclick = True
  5886. def on_mouse_move_over_plot(self, event, origin_click=None):
  5887. """
  5888. Callback for the mouse motion event over the plot.
  5889. :param event: Contains information about the event.
  5890. :param origin_click
  5891. :return: None
  5892. """
  5893. # So it can receive key presses
  5894. self.plotcanvas.native.setFocus()
  5895. self.pos_jump = event.pos
  5896. self.ui.popMenu.mouse_is_panning = False
  5897. if not origin_click:
  5898. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5899. if event.button == 2 and event.is_dragging == 1:
  5900. self.ui.popMenu.mouse_is_panning = True
  5901. return
  5902. if self.rel_point1 is not None:
  5903. try: # May fail in case mouse not within axes
  5904. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5905. if self.grid_status() == True:
  5906. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5907. self.app_cursor.enabled = True
  5908. # Update cursor
  5909. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5910. else:
  5911. pos = (pos_canvas[0], pos_canvas[1])
  5912. self.app_cursor.enabled = False
  5913. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5914. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5915. dx = pos[0] - self.rel_point1[0]
  5916. dy = pos[1] - self.rel_point1[1]
  5917. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5918. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5919. self.mouse = [pos[0], pos[1]]
  5920. # if the mouse is moved and the LMB is clicked then the action is a selection
  5921. if event.is_dragging == 1 and event.button == 1:
  5922. self.delete_selection_shape()
  5923. if dx < 0:
  5924. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5925. face_color=self.defaults['global_alt_sel_fill'])
  5926. self.selection_type = False
  5927. else:
  5928. self.draw_moving_selection_shape(self.pos, pos)
  5929. self.selection_type = True
  5930. # hover effect - enabled in Preferences -> General -> GUI Settings
  5931. if self.defaults['global_hover']:
  5932. for obj in self.collection.get_list():
  5933. try:
  5934. # select the object(s) only if it is enabled (plotted)
  5935. if obj.options['plot']:
  5936. if obj not in self.collection.get_selected():
  5937. poly_obj = Polygon(
  5938. [(obj.options['xmin'], obj.options['ymin']),
  5939. (obj.options['xmax'], obj.options['ymin']),
  5940. (obj.options['xmax'], obj.options['ymax']),
  5941. (obj.options['xmin'], obj.options['ymax'])]
  5942. )
  5943. if Point(pos).within(poly_obj):
  5944. if obj.isHovering is False:
  5945. obj.isHovering = True
  5946. obj.notHovering = True
  5947. # create the selection box around the selected object
  5948. self.draw_hover_shape(obj, color='#d1e0e0')
  5949. else:
  5950. if obj.notHovering is True:
  5951. obj.notHovering = False
  5952. obj.isHovering = False
  5953. self.delete_hover_shape()
  5954. except:
  5955. # the Exception here will happen if we try to select on screen and we have an
  5956. # newly (and empty) just created Geometry or Excellon object that do not have the
  5957. # xmin, xmax, ymin, ymax options.
  5958. # In this case poly_obj creation (see above) will fail
  5959. pass
  5960. except:
  5961. self.ui.position_label.setText("")
  5962. self.ui.rel_position_label.setText("")
  5963. self.mouse = None
  5964. def on_mouse_click_release_over_plot(self, event):
  5965. """
  5966. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5967. and has been registered in ''self.__init__()''.
  5968. :param event: contains information about the event.
  5969. :return:
  5970. """
  5971. pos = 0, 0
  5972. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5973. if self.grid_status() == True:
  5974. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5975. else:
  5976. pos = (pos_canvas[0], pos_canvas[1])
  5977. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5978. # canvas menu
  5979. if event.button == 2: # right click
  5980. if self.ui.popMenu.mouse_is_panning is False:
  5981. self.cursor = QtGui.QCursor()
  5982. self.populate_cmenu_grids()
  5983. self.ui.popMenu.popup(self.cursor.pos())
  5984. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5985. # selection and then select a type of selection ("enclosing" or "touching")
  5986. try:
  5987. if event.button == 1: # left click
  5988. if self.doubleclick is True:
  5989. self.doubleclick = False
  5990. if self.collection.get_selected():
  5991. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5992. if self.ui.splitter.sizes()[0] == 0:
  5993. self.ui.splitter.setSizes([1, 1])
  5994. # delete the selection shape(S) as it may be in the way
  5995. self.delete_selection_shape()
  5996. self.delete_hover_shape()
  5997. else:
  5998. if self.selection_type is not None:
  5999. self.selection_area_handler(self.pos, pos, self.selection_type)
  6000. self.selection_type = None
  6001. else:
  6002. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6003. if key_modifier == QtCore.Qt.ShiftModifier:
  6004. mod_key = 'Shift'
  6005. elif key_modifier == QtCore.Qt.ControlModifier:
  6006. mod_key = 'Control'
  6007. else:
  6008. mod_key = None
  6009. if mod_key == self.defaults["global_mselect_key"]:
  6010. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6011. # deselect, and if it's not selected then it will be selected
  6012. # If there is no active command (self.command_active is None) then we check if we clicked
  6013. # on a object by checking the bounding limits against mouse click position
  6014. if self.command_active is None:
  6015. self.select_objects(key='CTRL')
  6016. self.delete_hover_shape()
  6017. else:
  6018. # If there is no active command (self.command_active is None) then we check if we clicked
  6019. # on a object by checking the bounding limits against mouse click position
  6020. if self.command_active is None:
  6021. self.select_objects()
  6022. self.delete_hover_shape()
  6023. except Exception as e:
  6024. log.warning("Error: %s" % str(e))
  6025. return
  6026. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6027. """
  6028. :param start_pos: mouse position when the selection LMB click was done
  6029. :param end_pos: mouse position when the left mouse button is released
  6030. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6031. :return:
  6032. """
  6033. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6034. self.delete_selection_shape()
  6035. for obj in self.collection.get_list():
  6036. try:
  6037. # select the object(s) only if it is enabled (plotted)
  6038. if obj.options['plot']:
  6039. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6040. (obj.options['xmax'], obj.options['ymin']),
  6041. (obj.options['xmax'], obj.options['ymax']),
  6042. (obj.options['xmin'], obj.options['ymax'])])
  6043. if sel_type is True:
  6044. if poly_obj.within(poly_selection):
  6045. # create the selection box around the selected object
  6046. if self.defaults['global_selection_shape'] is True:
  6047. self.draw_selection_shape(obj)
  6048. self.collection.set_active(obj.options['name'])
  6049. else:
  6050. if poly_selection.intersects(poly_obj):
  6051. # create the selection box around the selected object
  6052. if self.defaults['global_selection_shape'] is True:
  6053. self.draw_selection_shape(obj)
  6054. self.collection.set_active(obj.options['name'])
  6055. except Exception as e:
  6056. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6057. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6058. # In this case poly_obj creation (see above) will fail
  6059. log.debug("App.selection_area_handler() --> %s" % str(e))
  6060. def select_objects(self, key=None):
  6061. # list where we store the overlapped objects under our mouse left click position
  6062. objects_under_the_click_list = []
  6063. # Populate the list with the overlapped objects on the click position
  6064. curr_x, curr_y = self.pos
  6065. for obj in self.all_objects_list:
  6066. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6067. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6068. if obj.options['name'] not in objects_under_the_click_list:
  6069. if obj.options['plot']:
  6070. # add objects to the objects_under_the_click list only if the object is plotted
  6071. # (active and not disabled)
  6072. objects_under_the_click_list.append(obj.options['name'])
  6073. try:
  6074. # If there is no element in the overlapped objects list then make everyone inactive
  6075. # because we selected "nothing"
  6076. if not objects_under_the_click_list:
  6077. self.collection.set_all_inactive()
  6078. # delete the possible selection box around a possible selected object
  6079. self.delete_selection_shape()
  6080. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6081. # only when working on App
  6082. if self.call_source == 'app':
  6083. if self.click_noproject is False:
  6084. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6085. else:
  6086. # restore auto open the Project Tab
  6087. self.click_noproject = False
  6088. # delete any text in the status bar, implicitly the last object name that was selected
  6089. self.inform.emit("")
  6090. else:
  6091. self.call_source = 'app'
  6092. else:
  6093. # case when there is only an object under the click and we toggle it
  6094. if len(objects_under_the_click_list) == 1:
  6095. if self.collection.get_active() is None:
  6096. self.collection.set_active(objects_under_the_click_list[0])
  6097. # create the selection box around the selected object
  6098. curr_sel_obj = self.collection.get_active()
  6099. if self.defaults['global_selection_shape'] is True:
  6100. self.draw_selection_shape(curr_sel_obj)
  6101. # self.inform.emit('[selected] %s: %s selected' %
  6102. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6103. if curr_sel_obj.kind == 'gerber':
  6104. self.inform.emit(
  6105. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6106. color='green', name=str(curr_sel_obj.options['name'])))
  6107. elif curr_sel_obj.kind == 'excellon':
  6108. self.inform.emit(
  6109. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6110. color='brown', name=str(curr_sel_obj.options['name'])))
  6111. elif curr_sel_obj.kind == 'cncjob':
  6112. self.inform.emit(
  6113. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6114. color='blue', name=str(curr_sel_obj.options['name'])))
  6115. elif curr_sel_obj.kind == 'geometry':
  6116. self.inform.emit(
  6117. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6118. color='red', name=str(curr_sel_obj.options['name'])))
  6119. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6120. self.collection.set_all_inactive()
  6121. self.delete_selection_shape()
  6122. self.collection.set_active(objects_under_the_click_list[0])
  6123. # create the selection box around the selected object
  6124. curr_sel_obj = self.collection.get_active()
  6125. if self.defaults['global_selection_shape'] is True:
  6126. self.draw_selection_shape(curr_sel_obj)
  6127. # self.inform.emit('[selected] %s: %s selected' %
  6128. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6129. if curr_sel_obj.kind == 'gerber':
  6130. self.inform.emit(
  6131. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6132. color='green', name=str(curr_sel_obj.options['name'])))
  6133. elif curr_sel_obj.kind == 'excellon':
  6134. self.inform.emit(
  6135. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6136. color='brown', name=str(curr_sel_obj.options['name'])))
  6137. elif curr_sel_obj.kind == 'cncjob':
  6138. self.inform.emit(
  6139. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6140. color='blue', name=str(curr_sel_obj.options['name'])))
  6141. elif curr_sel_obj.kind == 'geometry':
  6142. self.inform.emit(
  6143. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6144. color='red', name=str(curr_sel_obj.options['name'])))
  6145. else:
  6146. self.collection.set_all_inactive()
  6147. self.delete_selection_shape()
  6148. if self.call_source == 'app':
  6149. # delete any text in the status bar, implicitly the last object name that was selected
  6150. self.inform.emit("")
  6151. else:
  6152. self.call_source = 'app'
  6153. else:
  6154. # If there is no selected object
  6155. # make active the first element of the overlapped objects list
  6156. if self.collection.get_active() is None:
  6157. self.collection.set_active(objects_under_the_click_list[0])
  6158. name_sel_obj = self.collection.get_active().options['name']
  6159. # In case that there is a selected object but it is not in the overlapped object list
  6160. # make that object inactive and activate the first element in the overlapped object list
  6161. if name_sel_obj not in objects_under_the_click_list:
  6162. self.collection.set_inactive(name_sel_obj)
  6163. name_sel_obj = objects_under_the_click_list[0]
  6164. self.collection.set_active(name_sel_obj)
  6165. else:
  6166. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6167. self.collection.set_all_inactive()
  6168. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6169. len(objects_under_the_click_list)])
  6170. curr_sel_obj = self.collection.get_active()
  6171. # delete the possible selection box around a possible selected object
  6172. self.delete_selection_shape()
  6173. # create the selection box around the selected object
  6174. if self.defaults['global_selection_shape'] is True:
  6175. self.draw_selection_shape(curr_sel_obj)
  6176. # self.inform.emit('[selected] %s: %s selected' %
  6177. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6178. if curr_sel_obj.kind == 'gerber':
  6179. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6180. color='green', name=str(curr_sel_obj.options['name'])))
  6181. elif curr_sel_obj.kind == 'excellon':
  6182. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6183. color='brown', name=str(curr_sel_obj.options['name'])))
  6184. elif curr_sel_obj.kind == 'cncjob':
  6185. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6186. color='blue', name=str(curr_sel_obj.options['name'])))
  6187. elif curr_sel_obj.kind == 'geometry':
  6188. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6189. color='red', name=str(curr_sel_obj.options['name'])))
  6190. # for obj in self.collection.get_list():
  6191. # obj.plot()
  6192. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6193. # TODO: on selected objects change the object colors and do not draw the selection box
  6194. # self.plotcanvas.update() # this updates the canvas
  6195. except Exception as e:
  6196. log.error("[ERROR] Something went bad. %s" % str(e))
  6197. return
  6198. def delete_hover_shape(self):
  6199. self.hover_shapes.clear()
  6200. self.hover_shapes.redraw()
  6201. def draw_hover_shape(self, sel_obj, color=None):
  6202. """
  6203. :param sel_obj: the object for which the hover shape must be drawn
  6204. :return:
  6205. """
  6206. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6207. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6208. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6209. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6210. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6211. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6212. hover_rect = hover_rect.buffer(-0.1)
  6213. hover_rect = hover_rect.buffer(0.2)
  6214. else:
  6215. hover_rect = hover_rect.buffer(-0.00393)
  6216. hover_rect = hover_rect.buffer(0.00787)
  6217. if color:
  6218. face = Color(color)
  6219. face.alpha = 0.2
  6220. outline = Color(color, alpha=0.8)
  6221. else:
  6222. face = Color(self.defaults['global_sel_fill'])
  6223. face.alpha = 0.2
  6224. outline = self.defaults['global_sel_line']
  6225. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6226. def delete_selection_shape(self):
  6227. self.move_tool.sel_shapes.clear()
  6228. self.move_tool.sel_shapes.redraw()
  6229. def draw_selection_shape(self, sel_obj, color=None):
  6230. """
  6231. :param sel_obj: the object for which the selection shape must be drawn
  6232. :return:
  6233. """
  6234. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6235. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6236. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6237. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6238. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6239. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6240. sel_rect = sel_rect.buffer(-0.1)
  6241. sel_rect = sel_rect.buffer(0.2)
  6242. else:
  6243. sel_rect = sel_rect.buffer(-0.00393)
  6244. sel_rect = sel_rect.buffer(0.00787)
  6245. if color:
  6246. face = Color(color, alpha=0.2)
  6247. outline = Color(color, alpha=0.8)
  6248. else:
  6249. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6250. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6251. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6252. color=outline,
  6253. face_color=face,
  6254. update=True,
  6255. layer=0,
  6256. tolerance=None))
  6257. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6258. """
  6259. :param old_coords: old coordinates
  6260. :param coords: new coordinates
  6261. :return:
  6262. """
  6263. if 'color' in kwargs:
  6264. color = kwargs['color']
  6265. else:
  6266. color = self.defaults['global_sel_line']
  6267. if 'face_color' in kwargs:
  6268. face_color = kwargs['face_color']
  6269. else:
  6270. face_color = self.defaults['global_sel_fill']
  6271. if 'face_alpha' in kwargs:
  6272. face_alpha = kwargs['face_alpha']
  6273. else:
  6274. face_alpha = 0.3
  6275. x0, y0 = old_coords
  6276. x1, y1 = coords
  6277. pt1 = (x0, y0)
  6278. pt2 = (x1, y0)
  6279. pt3 = (x1, y1)
  6280. pt4 = (x0, y1)
  6281. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6282. color_t = Color(face_color)
  6283. color_t.alpha = face_alpha
  6284. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6285. layer=0, tolerance=None)
  6286. def on_file_new_click(self):
  6287. if self.collection.get_list() and self.should_we_save:
  6288. msgbox = QtWidgets.QMessageBox()
  6289. # msgbox.setText("<B>Save changes ...</B>")
  6290. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6291. "Creating a New project will delete them.\n"
  6292. "Do you want to Save the project?"))
  6293. msgbox.setWindowTitle(_("Save changes"))
  6294. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6295. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6296. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6297. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6298. msgbox.setDefaultButton(bt_yes)
  6299. msgbox.exec_()
  6300. response = msgbox.clickedButton()
  6301. if response == bt_yes:
  6302. self.on_file_saveprojectas()
  6303. elif response == bt_cancel:
  6304. return
  6305. elif response == bt_no:
  6306. self.on_file_new()
  6307. else:
  6308. self.on_file_new()
  6309. self.inform.emit('[success] %s...' %
  6310. _("New Project created"))
  6311. def on_file_new(self):
  6312. """
  6313. Callback for menu item File->New. Returns the application to its
  6314. startup state. This method is thread-safe.
  6315. :return: None
  6316. """
  6317. self.report_usage("on_file_new")
  6318. # Remove everything from memory
  6319. App.log.debug("on_file_new()")
  6320. if self.call_source != 'app':
  6321. self.editor2object(cleanup=True)
  6322. # ## EDITOR section
  6323. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6324. self.exc_editor = FlatCAMExcEditor(self)
  6325. self.grb_editor = FlatCAMGrbEditor(self)
  6326. # Clear pool
  6327. self.clear_pool()
  6328. for obj in self.collection.get_list():
  6329. # delete shapes left drawn from mark shape_collections, if any
  6330. if isinstance(obj, FlatCAMGerber):
  6331. try:
  6332. obj.mark_shapes.enabled = False
  6333. obj.mark_shapes.clear(update=True)
  6334. except AttributeError:
  6335. pass
  6336. # also delete annotation shapes, if any
  6337. elif isinstance(obj, FlatCAMCNCjob):
  6338. try:
  6339. obj.annotation.enabled = False
  6340. obj.annotation.clear(update=True)
  6341. except AttributeError:
  6342. pass
  6343. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6344. self.init_tcl()
  6345. self.delete_selection_shape()
  6346. self.collection.delete_all()
  6347. self.setup_component_editor()
  6348. # Clear project filename
  6349. self.project_filename = None
  6350. # Load the application defaults
  6351. self.load_defaults(filename='current_defaults')
  6352. # Re-fresh project options
  6353. self.on_options_app2project()
  6354. # Init Tools
  6355. self.init_tools()
  6356. # Close any Tabs opened in the Plot Tab Area section
  6357. for index in range(self.ui.plot_tab_area.count()):
  6358. self.ui.plot_tab_area.closeTab(index)
  6359. # for whatever reason previous command does not close the last tab so I do it manually
  6360. self.ui.plot_tab_area.closeTab(0)
  6361. # # And then add again the Plot Area
  6362. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6363. self.ui.plot_tab_area.protectTab(0)
  6364. # take the focus of the Notebook on Project Tab.
  6365. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6366. self.set_ui_title(name=_("New Project - Not saved"))
  6367. def obj_properties(self):
  6368. self.report_usage("obj_properties()")
  6369. self.properties_tool.run(toggle=False)
  6370. def on_project_context_save(self):
  6371. obj = self.collection.get_active()
  6372. if type(obj) == FlatCAMGeometry:
  6373. self.on_file_exportdxf()
  6374. elif type(obj) == FlatCAMExcellon:
  6375. self.on_file_saveexcellon()
  6376. elif type(obj) == FlatCAMCNCjob:
  6377. obj.on_exportgcode_button_click()
  6378. elif type(obj) == FlatCAMGerber:
  6379. self.on_file_savegerber()
  6380. def obj_move(self):
  6381. self.report_usage("obj_move()")
  6382. self.move_tool.run(toggle=False)
  6383. def on_fileopengerber(self, checked=None, name=None):
  6384. """
  6385. File menu callback for opening a Gerber.
  6386. :return: None
  6387. """
  6388. self.report_usage("on_fileopengerber")
  6389. App.log.debug("on_fileopengerber()")
  6390. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6391. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6392. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6393. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6394. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6395. "*.mil);;" \
  6396. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6397. "Allegro Files (*.art);;" \
  6398. "Mentor Files (*.pho *.gdo);;" \
  6399. "All Files (*.*)"
  6400. if name is None:
  6401. try:
  6402. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6403. directory=self.get_last_folder(),
  6404. filter=_filter_)
  6405. except TypeError:
  6406. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6407. filenames = [str(filename) for filename in filenames]
  6408. else:
  6409. filenames = [name]
  6410. if len(filenames) == 0:
  6411. self.inform.emit('[WARNING_NOTCL] %s' %
  6412. _("Open Gerber cancelled."))
  6413. else:
  6414. for filename in filenames:
  6415. if filename != '':
  6416. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6417. def on_fileopenexcellon(self, checked=None, name=None):
  6418. """
  6419. File menu callback for opening an Excellon file.
  6420. :return: None
  6421. """
  6422. self.report_usage("on_fileopenexcellon")
  6423. App.log.debug("on_fileopenexcellon()")
  6424. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6425. "All Files (*.*)"
  6426. if name is None:
  6427. try:
  6428. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6429. directory=self.get_last_folder(),
  6430. filter=_filter_)
  6431. except TypeError:
  6432. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6433. filenames = [str(filename) for filename in filenames]
  6434. else:
  6435. filenames = [str(name)]
  6436. if len(filenames) == 0:
  6437. self.inform.emit('[WARNING_NOTCL]%s' %
  6438. _(" Open Excellon cancelled."))
  6439. else:
  6440. for filename in filenames:
  6441. if filename != '':
  6442. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6443. def on_fileopengcode(self, checked=None, name=None):
  6444. """
  6445. File menu call back for opening gcode.
  6446. :return: None
  6447. """
  6448. self.report_usage("on_fileopengcode")
  6449. App.log.debug("on_fileopengcode()")
  6450. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6451. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6452. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6453. "All Files (*.*)"
  6454. if name is None:
  6455. try:
  6456. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6457. directory=self.get_last_folder(),
  6458. filter=_filter_)
  6459. except TypeError:
  6460. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6461. filenames = [str(filename) for filename in filenames]
  6462. else:
  6463. filenames = [name]
  6464. if len(filenames) == 0:
  6465. self.inform.emit('[WARNING_NOTCL] %s' %
  6466. _("Open G-Code cancelled."))
  6467. else:
  6468. for filename in filenames:
  6469. if filename != '':
  6470. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6471. def on_file_openproject(self, checked=None):
  6472. """
  6473. File menu callback for opening a project.
  6474. :return: None
  6475. """
  6476. self.report_usage("on_file_openproject")
  6477. App.log.debug("on_file_openproject()")
  6478. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6479. try:
  6480. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6481. directory=self.get_last_folder(), filter=_filter_)
  6482. except TypeError:
  6483. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6484. # The Qt methods above will return a QString which can cause problems later.
  6485. # So far json.dump() will fail to serialize it.
  6486. # TODO: Improve the serialization methods and remove this fix.
  6487. filename = str(filename)
  6488. if filename == "":
  6489. self.inform.emit('[WARNING_NOTCL] %s' %
  6490. _("Open Project cancelled."))
  6491. else:
  6492. # self.worker_task.emit({'fcn': self.open_project,
  6493. # 'params': [filename]})
  6494. # The above was failing because open_project() is not
  6495. # thread safe. The new_project()
  6496. self.open_project(filename)
  6497. def on_file_openconfig(self, checked=None):
  6498. """
  6499. File menu callback for opening a config file.
  6500. :return: None
  6501. """
  6502. self.report_usage("on_file_openconfig")
  6503. App.log.debug("on_file_openconfig()")
  6504. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6505. try:
  6506. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6507. directory=self.data_path, filter=_filter_)
  6508. except TypeError:
  6509. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6510. filter=_filter_)
  6511. if filename == "":
  6512. self.inform.emit('[WARNING_NOTCL] %s' %
  6513. _("Open Config cancelled."))
  6514. else:
  6515. self.open_config_file(filename)
  6516. def on_file_exportsvg(self):
  6517. """
  6518. Callback for menu item File->Export SVG.
  6519. :return: None
  6520. """
  6521. self.report_usage("on_file_exportsvg")
  6522. App.log.debug("on_file_exportsvg()")
  6523. obj = self.collection.get_active()
  6524. if obj is None:
  6525. self.inform.emit('[WARNING_NOTCL] %s' %
  6526. _("No object selected."))
  6527. msg = _("Please Select a Geometry object to export")
  6528. msgbox = QtWidgets.QMessageBox()
  6529. msgbox.setInformativeText(msg)
  6530. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6531. msgbox.setDefaultButton(bt_ok)
  6532. msgbox.exec_()
  6533. return
  6534. # Check for more compatible types and add as required
  6535. if (not isinstance(obj, FlatCAMGeometry)
  6536. and not isinstance(obj, FlatCAMGerber)
  6537. and not isinstance(obj, FlatCAMCNCjob)
  6538. and not isinstance(obj, FlatCAMExcellon)):
  6539. msg = '[ERROR_NOTCL] %s' % \
  6540. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6541. msgbox = QtWidgets.QMessageBox()
  6542. msgbox.setInformativeText(msg)
  6543. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6544. msgbox.setDefaultButton(bt_ok)
  6545. msgbox.exec_()
  6546. return
  6547. name = obj.options["name"]
  6548. _filter = "SVG File (*.svg);;All Files (*.*)"
  6549. try:
  6550. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6551. caption=_("Export SVG"),
  6552. directory=self.get_last_save_folder() + '/' + str(name),
  6553. filter=_filter)
  6554. except TypeError:
  6555. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6556. filename = str(filename)
  6557. if filename == "":
  6558. self.inform.emit('[WARNING_NOTCL]%s' %
  6559. _(" Export SVG cancelled."))
  6560. return
  6561. else:
  6562. self.export_svg(name, filename)
  6563. if self.defaults["global_open_style"] is False:
  6564. self.file_opened.emit("SVG", filename)
  6565. self.file_saved.emit("SVG", filename)
  6566. def on_file_exportpng(self):
  6567. self.report_usage("on_file_exportpng")
  6568. App.log.debug("on_file_exportpng()")
  6569. self.date = str(datetime.today()).rpartition('.')[0]
  6570. self.date = ''.join(c for c in self.date if c not in ':-')
  6571. self.date = self.date.replace(' ', '_')
  6572. image = _screenshot()
  6573. data = np.asarray(image)
  6574. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6575. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6576. _('Data must be a 3D array with last dimension 3 or 4'))
  6577. return
  6578. filter_ = "PNG File (*.png);;All Files (*.*)"
  6579. try:
  6580. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6581. caption=_("Export PNG Image"),
  6582. directory=self.get_last_save_folder() + '/png_' + self.date,
  6583. filter=filter_)
  6584. except TypeError:
  6585. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6586. filename = str(filename)
  6587. if filename == "":
  6588. self.inform.emit(_("Export PNG cancelled."))
  6589. return
  6590. else:
  6591. write_png(filename, data)
  6592. if self.defaults["global_open_style"] is False:
  6593. self.file_opened.emit("png", filename)
  6594. self.file_saved.emit("png", filename)
  6595. def on_file_savegerber(self):
  6596. """
  6597. Callback for menu item in Project context menu.
  6598. :return: None
  6599. """
  6600. self.report_usage("on_file_savegerber")
  6601. App.log.debug("on_file_savegerber()")
  6602. obj = self.collection.get_active()
  6603. if obj is None:
  6604. self.inform.emit('[WARNING_NOTCL] %s' %
  6605. _("No object selected. Please select an Gerber object to export."))
  6606. return
  6607. # Check for more compatible types and add as required
  6608. if not isinstance(obj, FlatCAMGerber):
  6609. self.inform.emit('[ERROR_NOTCL] %s' %
  6610. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6611. return
  6612. name = self.collection.get_active().options["name"]
  6613. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6614. try:
  6615. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6616. caption="Save Gerber source file",
  6617. directory=self.get_last_save_folder() + '/' + name,
  6618. filter=_filter)
  6619. except TypeError:
  6620. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6621. filename = str(filename)
  6622. if filename == "":
  6623. self.inform.emit('[WARNING_NOTCL] %s' %
  6624. _("Save Gerber source file cancelled."))
  6625. return
  6626. else:
  6627. self.save_source_file(name, filename)
  6628. if self.defaults["global_open_style"] is False:
  6629. self.file_opened.emit("Gerber", filename)
  6630. self.file_saved.emit("Gerber", filename)
  6631. def on_file_saveexcellon(self):
  6632. """
  6633. Callback for menu item in project context menu.
  6634. :return: None
  6635. """
  6636. self.report_usage("on_file_saveexcellon")
  6637. App.log.debug("on_file_saveexcellon()")
  6638. obj = self.collection.get_active()
  6639. if obj is None:
  6640. self.inform.emit('[WARNING_NOTCL] %s' %
  6641. _("No object selected. Please select an Excellon object to export."))
  6642. return
  6643. # Check for more compatible types and add as required
  6644. if not isinstance(obj, FlatCAMExcellon):
  6645. self.inform.emit('[ERROR_NOTCL] %s' %
  6646. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6647. return
  6648. name = self.collection.get_active().options["name"]
  6649. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6650. try:
  6651. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6652. caption=_("Save Excellon source file"),
  6653. directory=self.get_last_save_folder() + '/' + name,
  6654. filter=_filter)
  6655. except TypeError:
  6656. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6657. filename = str(filename)
  6658. if filename == "":
  6659. self.inform.emit('[WARNING_NOTCL] %s' %
  6660. _("Saving Excellon source file cancelled."))
  6661. return
  6662. else:
  6663. self.save_source_file(name, filename)
  6664. if self.defaults["global_open_style"] is False:
  6665. self.file_opened.emit("Excellon", filename)
  6666. self.file_saved.emit("Excellon", filename)
  6667. def on_file_exportexcellon(self):
  6668. """
  6669. Callback for menu item File->Export->Excellon.
  6670. :return: None
  6671. """
  6672. self.report_usage("on_file_exportexcellon")
  6673. App.log.debug("on_file_exportexcellon()")
  6674. obj = self.collection.get_active()
  6675. if obj is None:
  6676. self.inform.emit('[WARNING_NOTCL] %s' %
  6677. _("No object selected. Please Select an Excellon object to export."))
  6678. return
  6679. # Check for more compatible types and add as required
  6680. if not isinstance(obj, FlatCAMExcellon):
  6681. self.inform.emit('[ERROR_NOTCL] %s' %
  6682. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6683. return
  6684. name = self.collection.get_active().options["name"]
  6685. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6686. try:
  6687. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6688. caption=_("Export Excellon"),
  6689. directory=self.get_last_save_folder() + '/' + name,
  6690. filter=_filter)
  6691. except TypeError:
  6692. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6693. filename = str(filename)
  6694. if filename == "":
  6695. self.inform.emit('[WARNING_NOTCL] %s' %
  6696. _("Export Excellon cancelled."))
  6697. return
  6698. else:
  6699. self.export_excellon(name, filename)
  6700. if self.defaults["global_open_style"] is False:
  6701. self.file_opened.emit("Excellon", filename)
  6702. self.file_saved.emit("Excellon", filename)
  6703. def on_file_exportgerber(self):
  6704. """
  6705. Callback for menu item File->Export->Gerber.
  6706. :return: None
  6707. """
  6708. self.report_usage("on_file_exportgerber")
  6709. App.log.debug("on_file_exportgerber()")
  6710. obj = self.collection.get_active()
  6711. if obj is None:
  6712. self.inform.emit('[WARNING_NOTCL] %s' %
  6713. _("No object selected. Please Select an Gerber object to export."))
  6714. return
  6715. # Check for more compatible types and add as required
  6716. if not isinstance(obj, FlatCAMGerber):
  6717. self.inform.emit('[ERROR_NOTCL] %s' %
  6718. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6719. return
  6720. name = self.collection.get_active().options["name"]
  6721. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6722. try:
  6723. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6724. caption=_("Export Gerber"),
  6725. directory=self.get_last_save_folder() + '/' + name,
  6726. filter=_filter_)
  6727. except TypeError:
  6728. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6729. filename = str(filename)
  6730. if filename == "":
  6731. self.inform.emit('[WARNING_NOTCL] %s' %
  6732. _("Export Gerber cancelled."))
  6733. return
  6734. else:
  6735. self.export_gerber(name, filename)
  6736. if self.defaults["global_open_style"] is False:
  6737. self.file_opened.emit("Gerber", filename)
  6738. self.file_saved.emit("Gerber", filename)
  6739. def on_file_exportdxf(self):
  6740. """
  6741. Callback for menu item File->Export DXF.
  6742. :return: None
  6743. """
  6744. self.report_usage("on_file_exportdxf")
  6745. App.log.debug("on_file_exportdxf()")
  6746. obj = self.collection.get_active()
  6747. if obj is None:
  6748. self.inform.emit('[WARNING_NOTCL] %s' %
  6749. _("No object selected."))
  6750. msg = _("Please Select a Geometry object to export")
  6751. msgbox = QtWidgets.QMessageBox()
  6752. msgbox.setInformativeText(msg)
  6753. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6754. msgbox.setDefaultButton(bt_ok)
  6755. msgbox.exec_()
  6756. return
  6757. # Check for more compatible types and add as required
  6758. if not isinstance(obj, FlatCAMGeometry):
  6759. msg = '[ERROR_NOTCL] %s' % \
  6760. _("Only Geometry objects can be used.")
  6761. msgbox = QtWidgets.QMessageBox()
  6762. msgbox.setInformativeText(msg)
  6763. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6764. msgbox.setDefaultButton(bt_ok)
  6765. msgbox.exec_()
  6766. return
  6767. name = self.collection.get_active().options["name"]
  6768. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6769. try:
  6770. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6771. caption=_("Export DXF"),
  6772. directory=self.get_last_save_folder() + '/' + name,
  6773. filter=_filter_)
  6774. except TypeError:
  6775. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6776. filter=_filter_)
  6777. filename = str(filename)
  6778. if filename == "":
  6779. self.inform.emit('[WARNING_NOTCL] %s' %
  6780. _("Export DXF cancelled."))
  6781. return
  6782. else:
  6783. self.export_dxf(name, filename)
  6784. if self.defaults["global_open_style"] is False:
  6785. self.file_opened.emit("DXF", filename)
  6786. self.file_saved.emit("DXF", filename)
  6787. def on_file_importsvg(self, type_of_obj):
  6788. """
  6789. Callback for menu item File->Import SVG.
  6790. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6791. :type type_of_obj: str
  6792. :return: None
  6793. """
  6794. self.report_usage("on_file_importsvg")
  6795. App.log.debug("on_file_importsvg()")
  6796. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6797. try:
  6798. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6799. directory=self.get_last_folder(), filter=_filter_)
  6800. except TypeError:
  6801. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6802. filter=_filter_)
  6803. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6804. type_of_obj = "geometry"
  6805. filenames = [str(filename) for filename in filenames]
  6806. if len(filenames) == 0:
  6807. self.inform.emit('[WARNING_NOTCL] %s' %
  6808. _("Open SVG cancelled."))
  6809. else:
  6810. for filename in filenames:
  6811. if filename != '':
  6812. self.worker_task.emit({'fcn': self.import_svg,
  6813. 'params': [filename, type_of_obj]})
  6814. def on_file_importdxf(self, type_of_obj):
  6815. """
  6816. Callback for menu item File->Import DXF.
  6817. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6818. :type type_of_obj: str
  6819. :return: None
  6820. """
  6821. self.report_usage("on_file_importdxf")
  6822. App.log.debug("on_file_importdxf()")
  6823. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6824. try:
  6825. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6826. directory=self.get_last_folder(),
  6827. filter=_filter_)
  6828. except TypeError:
  6829. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6830. filter=_filter_)
  6831. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6832. type_of_obj = "geometry"
  6833. filenames = [str(filename) for filename in filenames]
  6834. if len(filenames) == 0:
  6835. self.inform.emit('[WARNING_NOTCL] %s' %
  6836. _("Open DXF cancelled."))
  6837. else:
  6838. for filename in filenames:
  6839. if filename != '':
  6840. self.worker_task.emit({'fcn': self.import_dxf,
  6841. 'params': [filename, type_of_obj]})
  6842. # ###############################################################################################################
  6843. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6844. # ###############################################################################################################
  6845. def init_code_editor(self, name):
  6846. # Signals section
  6847. # Disconnect the old signals
  6848. try:
  6849. self.ui.buttonOpen.clicked.disconnect()
  6850. except TypeError:
  6851. pass
  6852. try:
  6853. self.ui.buttonSave.clicked.disconnect()
  6854. except TypeError:
  6855. pass
  6856. # add the tab if it was closed
  6857. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  6858. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6859. # delete the absolute and relative position and messages in the infobar
  6860. self.ui.position_label.setText("")
  6861. self.ui.rel_position_label.setText("")
  6862. # first clear previous text in text editor (if any)
  6863. self.ui.code_editor.clear()
  6864. self.ui.code_editor.setReadOnly(False)
  6865. self.toggle_codeeditor = True
  6866. self.ui.code_editor.completer_enable = False
  6867. self.ui.buttonRun.hide()
  6868. # make sure to keep a reference to the code editor
  6869. self.reference_code_editor = self.ui.code_editor
  6870. # Switch plot_area to CNCJob tab
  6871. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6872. def on_view_source(self):
  6873. self.inform.emit('%s' %
  6874. _("Viewing the source code of the selected object."))
  6875. self.proc_container.view.set_busy(_("Loading..."))
  6876. try:
  6877. obj = self.collection.get_active()
  6878. except Exception as e:
  6879. log.debug("App.on_view_source() --> %s" % str(e))
  6880. self.inform.emit('[WARNING_NOTCL] %s' %
  6881. _("Select an Gerber or Excellon file to view it's source file."))
  6882. return 'fail'
  6883. if obj.kind == 'gerber':
  6884. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6885. elif obj.kind == 'excellon':
  6886. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6887. elif obj.kind == 'cncjob':
  6888. "GCode Files (*.NC);;All Files (*.*)"
  6889. else:
  6890. flt = "All Files (*.*)"
  6891. self.init_code_editor(name=_("Source Editor"))
  6892. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6893. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6894. # then append the text from GCode to the text editor
  6895. if obj.kind == 'cncjob':
  6896. try:
  6897. file = obj.export_gcode(preamble='', postamble='', to_file=True)
  6898. if file == 'fail':
  6899. return 'fail'
  6900. except AttributeError:
  6901. self.inform.emit('[WARNING_NOTCL] %s' %
  6902. _("There is no selected object for which to see it's source file code."))
  6903. return 'fail'
  6904. else:
  6905. try:
  6906. file = StringIO(obj.source_file)
  6907. except AttributeError:
  6908. self.inform.emit('[WARNING_NOTCL] %s' %
  6909. _("There is no selected object for which to see it's source file code."))
  6910. return 'fail'
  6911. self.ui.cncjob_frame.hide()
  6912. try:
  6913. for line in file:
  6914. QtWidgets.QApplication.processEvents()
  6915. proc_line = str(line).strip('\n')
  6916. self.ui.code_editor.append(proc_line)
  6917. except Exception as e:
  6918. log.debug('App.on_view_source() -->%s' % str(e))
  6919. self.inform.emit('[ERROR] %s: %s' %
  6920. (_('Failed to load the source code for the selected object'), str(e)))
  6921. return
  6922. self.handleTextChanged()
  6923. self.ui.cncjob_frame.show()
  6924. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6925. self.proc_container.view.set_idle()
  6926. # self.ui.show()
  6927. def on_toggle_code_editor(self):
  6928. self.report_usage("on_toggle_code_editor()")
  6929. if self.toggle_codeeditor is False:
  6930. self.init_code_editor(name=_("Code Editor"))
  6931. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6932. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6933. else:
  6934. for idx in range(self.ui.plot_tab_area.count()):
  6935. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6936. self.ui.plot_tab_area.closeTab(idx)
  6937. break
  6938. self.toggle_codeeditor = False
  6939. def on_filenewscript(self):
  6940. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6941. self.init_code_editor(name=_("Script Editor"))
  6942. self.ui.code_editor.completer_enable = True
  6943. self.ui.code_editor.append(_(
  6944. "#\n"
  6945. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6946. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6947. "#\n\n"
  6948. "# FlatCAM commands list:\n"
  6949. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  6950. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  6951. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  6952. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  6953. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  6954. "# SubtractRectangle, Version, WriteGCode\n"
  6955. "#\n\n"
  6956. ))
  6957. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6958. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6959. self.ui.buttonRun.show()
  6960. try:
  6961. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  6962. except TypeError:
  6963. pass
  6964. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  6965. self.handleTextChanged()
  6966. self.ui.code_editor.show()
  6967. def on_fileopenscript(self):
  6968. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6969. try:
  6970. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6971. directory=self.get_last_folder(), filter=_filter_)
  6972. except TypeError:
  6973. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6974. # The Qt methods above will return a QString which can cause problems later.
  6975. # So far json.dump() will fail to serialize it.
  6976. # TODO: Improve the serialization methods and remove this fix.
  6977. filename = str(filename)
  6978. if filename == "":
  6979. self.inform.emit('[WARNING_NOTCL] %s' %
  6980. _("Open TCL script cancelled."))
  6981. else:
  6982. self.on_filenewscript()
  6983. try:
  6984. with open(filename, "r") as opened_script:
  6985. try:
  6986. for line in opened_script:
  6987. proc_line = str(line).strip('\n')
  6988. self.ui.code_editor.append(proc_line)
  6989. except Exception as e:
  6990. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6991. self.inform.emit('[ERROR] %s %s' %
  6992. (_('App.on_fileopenscript() -->'), str(e)))
  6993. return
  6994. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6995. self.handleTextChanged()
  6996. # self.ui.show()
  6997. except Exception as e:
  6998. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6999. def on_filerunscript(self, name=None):
  7000. """
  7001. File menu callback for loading and running a TCL script.
  7002. :return: None
  7003. """
  7004. self.report_usage("on_filerunscript")
  7005. App.log.debug("on_file_runscript()")
  7006. if name:
  7007. filename = name
  7008. else:
  7009. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7010. try:
  7011. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7012. directory=self.get_last_folder(), filter=_filter_)
  7013. except TypeError:
  7014. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7015. # The Qt methods above will return a QString which can cause problems later.
  7016. # So far json.dump() will fail to serialize it.
  7017. # TODO: Improve the serialization methods and remove this fix.
  7018. filename = str(filename)
  7019. if filename == "":
  7020. self.inform.emit('[WARNING_NOTCL] %s' %
  7021. _("Run TCL script cancelled."))
  7022. else:
  7023. try:
  7024. with open(filename, "r") as tcl_script:
  7025. cmd_line_shellfile_content = tcl_script.read()
  7026. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7027. except Exception as e:
  7028. log.debug("App.on_filerunscript() -> %s" % str(e))
  7029. sys.exit(2)
  7030. def on_file_saveproject(self):
  7031. """
  7032. Callback for menu item File->Save Project. Saves the project to
  7033. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7034. if set to None. The project is saved by calling ``self.save_project()``.
  7035. :return: None
  7036. """
  7037. self.report_usage("on_file_saveproject")
  7038. if self.project_filename is None:
  7039. self.on_file_saveprojectas()
  7040. else:
  7041. self.worker_task.emit({'fcn': self.save_project,
  7042. 'params': [self.project_filename]})
  7043. if self.defaults["global_open_style"] is False:
  7044. self.file_opened.emit("project", self.project_filename)
  7045. self.file_saved.emit("project", self.project_filename)
  7046. self.set_ui_title(name=self.project_filename)
  7047. self.should_we_save = False
  7048. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7049. """
  7050. Callback for menu item File->Save Project As... Opens a file
  7051. chooser and saves the project to the given file via
  7052. ``self.save_project()``.
  7053. :param make_copy if to be create a copy of the project; boolean
  7054. :param use_thread: if to be run in a separate thread; boolean
  7055. :param quit_action: if to be followed by quiting the application; boolean
  7056. :return: None
  7057. """
  7058. self.report_usage("on_file_saveprojectas")
  7059. self.date = str(datetime.today()).rpartition('.')[0]
  7060. self.date = ''.join(c for c in self.date if c not in ':-')
  7061. self.date = self.date.replace(' ', '_')
  7062. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7063. try:
  7064. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7065. caption=_("Save Project As ..."),
  7066. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7067. filter=filter_)
  7068. except TypeError:
  7069. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7070. filename = str(filename)
  7071. if filename == '':
  7072. self.inform.emit('[WARNING_NOTCL] %s' %
  7073. _("Save Project cancelled."))
  7074. return
  7075. try:
  7076. f = open(filename, 'r')
  7077. f.close()
  7078. except IOError:
  7079. pass
  7080. if use_thread is True:
  7081. self.worker_task.emit({'fcn': self.save_project,
  7082. 'params': [filename, quit_action]})
  7083. else:
  7084. self.save_project(filename, quit_action)
  7085. # self.save_project(filename)
  7086. if self.defaults["global_open_style"] is False:
  7087. self.file_opened.emit("project", filename)
  7088. self.file_saved.emit("project", filename)
  7089. if not make_copy:
  7090. self.project_filename = filename
  7091. self.set_ui_title(name=self.project_filename)
  7092. self.should_we_save = False
  7093. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7094. """
  7095. Exports a Geometry Object to an SVG file.
  7096. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7097. :param filename: Path to the SVG file to save to.
  7098. :param scale_factor: factor by which to change/scale the thickness of the features
  7099. :return:
  7100. """
  7101. self.report_usage("export_svg()")
  7102. if filename is None:
  7103. filename = self.defaults["global_last_save_folder"]
  7104. self.log.debug("export_svg()")
  7105. try:
  7106. obj = self.collection.get_by_name(str(obj_name))
  7107. except:
  7108. # TODO: The return behavior has not been established... should raise exception?
  7109. return "Could not retrieve object: %s" % obj_name
  7110. with self.proc_container.new(_("Exporting SVG")) as proc:
  7111. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7112. # Determine bounding area for svg export
  7113. bounds = obj.bounds()
  7114. size = obj.size()
  7115. # Convert everything to strings for use in the xml doc
  7116. svgwidth = str(size[0])
  7117. svgheight = str(size[1])
  7118. minx = str(bounds[0])
  7119. miny = str(bounds[1] - size[1])
  7120. uom = obj.units.lower()
  7121. # Add a SVG Header and footer to the svg output from shapely
  7122. # The transform flips the Y Axis so that everything renders
  7123. # properly within svg apps such as inkscape
  7124. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7125. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7126. svg_header += 'width="' + svgwidth + uom + '" '
  7127. svg_header += 'height="' + svgheight + uom + '" '
  7128. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7129. svg_header += '<g transform="scale(1,-1)">'
  7130. svg_footer = '</g> </svg>'
  7131. svg_elem = svg_header + exported_svg + svg_footer
  7132. # Parse the xml through a xml parser just to add line feeds
  7133. # and to make it look more pretty for the output
  7134. svgcode = parse_xml_string(svg_elem)
  7135. try:
  7136. with open(filename, 'w') as fp:
  7137. fp.write(svgcode.toprettyxml())
  7138. except PermissionError:
  7139. self.inform.emit('[WARNING] %s' %
  7140. _("Permission denied, saving not possible.\n"
  7141. "Most likely another app is holding the file open and not accessible."))
  7142. return 'fail'
  7143. if self.defaults["global_open_style"] is False:
  7144. self.file_opened.emit("SVG", filename)
  7145. self.file_saved.emit("SVG", filename)
  7146. self.inform.emit('[success] %s: %s' %
  7147. (_("SVG file exported to"), filename))
  7148. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7149. """
  7150. Exports a Geometry Object to an SVG file in negative.
  7151. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7152. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7153. :param filename: Path to the SVG file to save to.
  7154. :param boundary: thickness of a black border to surround all the features
  7155. :param scale_factor: factor by which to change/scale the thickness of the features
  7156. :param use_thread: if to be run in a separate thread; boolean
  7157. :return:
  7158. """
  7159. self.report_usage("export_negative()")
  7160. if filename is None:
  7161. filename = self.defaults["global_last_save_folder"]
  7162. self.log.debug("export_svg() negative")
  7163. try:
  7164. obj = self.collection.get_by_name(str(obj_name))
  7165. except:
  7166. # TODO: The return behavior has not been established... should raise exception?
  7167. return "Could not retrieve object: %s" % obj_name
  7168. try:
  7169. box = self.collection.get_by_name(str(box_name))
  7170. except:
  7171. # TODO: The return behavior has not been established... should raise exception?
  7172. return "Could not retrieve object: %s" % box_name
  7173. if box is None:
  7174. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7175. (_("No object Box. Using instead"), obj))
  7176. box = obj
  7177. def make_negative_film():
  7178. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7179. self.progress.emit(40)
  7180. # Determine bounding area for svg export
  7181. bounds = box.bounds()
  7182. size = box.size()
  7183. uom = obj.units.lower()
  7184. # Convert everything to strings for use in the xml doc
  7185. svgwidth = str(size[0] + (2 * boundary))
  7186. svgheight = str(size[1] + (2 * boundary))
  7187. minx = str(bounds[0] - boundary)
  7188. miny = str(bounds[1] + boundary + size[1])
  7189. miny_rect = str(bounds[1] - boundary)
  7190. # Add a SVG Header and footer to the svg output from shapely
  7191. # The transform flips the Y Axis so that everything renders
  7192. # properly within svg apps such as inkscape
  7193. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7194. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7195. svg_header += 'width="' + svgwidth + uom + '" '
  7196. svg_header += 'height="' + svgheight + uom + '" '
  7197. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7198. svg_header += '>'
  7199. svg_header += '<g transform="scale(1,-1)">'
  7200. svg_footer = '</g> </svg>'
  7201. self.progress.emit(60)
  7202. # Change the attributes of the exported SVG
  7203. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7204. # We set opacity to maximum
  7205. # We set the color to WHITE
  7206. root = ET.fromstring(exported_svg)
  7207. for child in root:
  7208. child.set('fill', '#FFFFFF')
  7209. child.set('opacity', '1.0')
  7210. child.set('stroke', '#FFFFFF')
  7211. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7212. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7213. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7214. first_svg_elem_tag = 'rect'
  7215. first_svg_elem_attribs = {
  7216. 'x': minx,
  7217. 'y': miny_rect,
  7218. 'width': svgwidth,
  7219. 'height': svgheight,
  7220. 'id': 'neg_rect',
  7221. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7222. }
  7223. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7224. exported_svg = ET.tostring(root)
  7225. svg_elem = svg_header + str(exported_svg) + svg_footer
  7226. self.progress.emit(80)
  7227. # Parse the xml through a xml parser just to add line feeds
  7228. # and to make it look more pretty for the output
  7229. doc = parse_xml_string(svg_elem)
  7230. try:
  7231. with open(filename, 'w') as fp:
  7232. fp.write(doc.toprettyxml())
  7233. except PermissionError:
  7234. self.inform.emit('[WARNING] %s' %
  7235. _("Permission denied, saving not possible.\n"
  7236. "Most likely another app is holding the file open and not accessible."))
  7237. return 'fail'
  7238. self.progress.emit(100)
  7239. if self.defaults["global_open_style"] is False:
  7240. self.file_opened.emit("SVG", filename)
  7241. self.file_saved.emit("SVG", filename)
  7242. self.inform.emit('[success] %s: %s' %
  7243. (_("SVG file exported to"), filename))
  7244. if use_thread is True:
  7245. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7246. def job_thread_film(app_obj):
  7247. try:
  7248. make_negative_film()
  7249. except Exception as e:
  7250. proc.done()
  7251. return
  7252. proc.done()
  7253. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7254. else:
  7255. make_negative_film()
  7256. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7257. """
  7258. Exports a Geometry Object to an SVG file in positive black.
  7259. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7260. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7261. :param filename: Path to the SVG file to save to.
  7262. :param scale_factor: factor by which to change/scale the thickness of the features
  7263. :param use_thread: if to be run in a separate thread; boolean
  7264. :return:
  7265. """
  7266. self.report_usage("export_svg_black()")
  7267. if filename is None:
  7268. filename = self.defaults["global_last_save_folder"]
  7269. self.log.debug("export_svg() black")
  7270. try:
  7271. obj = self.collection.get_by_name(str(obj_name))
  7272. except:
  7273. # TODO: The return behavior has not been established... should raise exception?
  7274. return "Could not retrieve object: %s" % obj_name
  7275. try:
  7276. box = self.collection.get_by_name(str(box_name))
  7277. except:
  7278. # TODO: The return behavior has not been established... should raise exception?
  7279. return "Could not retrieve object: %s" % box_name
  7280. if box is None:
  7281. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7282. (_("No object Box. Using instead"), obj))
  7283. box = obj
  7284. def make_black_film():
  7285. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7286. self.progress.emit(40)
  7287. # Change the attributes of the exported SVG
  7288. # We don't need stroke-width
  7289. # We set opacity to maximum
  7290. # We set the colour to WHITE
  7291. root = ET.fromstring(exported_svg)
  7292. for child in root:
  7293. child.set('fill', '#000000')
  7294. child.set('opacity', '1.0')
  7295. child.set('stroke', '#000000')
  7296. exported_svg = ET.tostring(root)
  7297. # Determine bounding area for svg export
  7298. bounds = box.bounds()
  7299. size = box.size()
  7300. # This contain the measure units
  7301. uom = obj.units.lower()
  7302. # Define a boundary around SVG of about 1.0mm (~39mils)
  7303. if uom in "mm":
  7304. boundary = 1.0
  7305. else:
  7306. boundary = 0.0393701
  7307. self.progress.emit(80)
  7308. # Convert everything to strings for use in the xml doc
  7309. svgwidth = str(size[0] + (2 * boundary))
  7310. svgheight = str(size[1] + (2 * boundary))
  7311. minx = str(bounds[0] - boundary)
  7312. miny = str(bounds[1] + boundary + size[1])
  7313. self.log.debug(minx)
  7314. self.log.debug(miny)
  7315. # Add a SVG Header and footer to the svg output from shapely
  7316. # The transform flips the Y Axis so that everything renders
  7317. # properly within svg apps such as inkscape
  7318. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7319. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7320. svg_header += 'width="' + svgwidth + uom + '" '
  7321. svg_header += 'height="' + svgheight + uom + '" '
  7322. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7323. svg_header += '>'
  7324. svg_header += '<g transform="scale(1,-1)">'
  7325. svg_footer = '</g> </svg>'
  7326. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7327. self.progress.emit(90)
  7328. # Parse the xml through a xml parser just to add line feeds
  7329. # and to make it look more pretty for the output
  7330. doc = parse_xml_string(svg_elem)
  7331. try:
  7332. with open(filename, 'w') as fp:
  7333. fp.write(doc.toprettyxml())
  7334. except PermissionError:
  7335. self.inform.emit('[WARNING] %s' %
  7336. _("Permission denied, saving not possible.\n"
  7337. "Most likely another app is holding the file open and not accessible."))
  7338. return 'fail'
  7339. self.progress.emit(100)
  7340. if self.defaults["global_open_style"] is False:
  7341. self.file_opened.emit("SVG", filename)
  7342. self.file_saved.emit("SVG", filename)
  7343. self.inform.emit('[success] %s: %s' %
  7344. (_("SVG file exported to"), filename))
  7345. if use_thread is True:
  7346. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7347. def job_thread_film(app_obj):
  7348. try:
  7349. make_black_film()
  7350. except Exception as e:
  7351. proc.done()
  7352. return
  7353. proc.done()
  7354. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7355. else:
  7356. make_black_film()
  7357. def save_source_file(self, obj_name, filename, use_thread=True):
  7358. """
  7359. Exports a FlatCAM Object to an Gerber/Excellon file.
  7360. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7361. :param filename: Path to the Gerber file to save to.
  7362. :param use_thread: if to be run in a separate thread
  7363. :return:
  7364. """
  7365. self.report_usage("save source file()")
  7366. if filename is None:
  7367. filename = self.defaults["global_last_save_folder"]
  7368. self.log.debug("save source file()")
  7369. obj = self.collection.get_by_name(obj_name)
  7370. file_string = StringIO(obj.source_file)
  7371. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7372. try:
  7373. with open(filename, 'w') as file:
  7374. file.writelines('G04*\n')
  7375. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7376. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7377. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7378. file.writelines('G04 Created on : %s*\n' % time_string)
  7379. for line in file_string:
  7380. file.writelines(line)
  7381. except PermissionError:
  7382. self.inform.emit('[WARNING] %s' %
  7383. _("Permission denied, saving not possible.\n"
  7384. "Most likely another app is holding the file open and not accessible."))
  7385. return 'fail'
  7386. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7387. """
  7388. Exports a Excellon Object to an Excellon file.
  7389. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7390. :param filename: Path to the Excellon file to save to.
  7391. :param use_thread: if to be run in a separate thread
  7392. :return:
  7393. """
  7394. self.report_usage("export_excellon()")
  7395. if filename is None:
  7396. filename = self.defaults["global_last_save_folder"]
  7397. self.log.debug("export_excellon()")
  7398. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7399. self.defaults["excellon_exp_decimals"]
  7400. )
  7401. units = ''
  7402. if local_use is None:
  7403. try:
  7404. obj = self.collection.get_by_name(str(obj_name))
  7405. except:
  7406. # TODO: The return behavior has not been established... should raise exception?
  7407. return "Could not retrieve object: %s" % obj_name
  7408. else:
  7409. obj = local_use
  7410. # updated units
  7411. eunits = self.defaults["excellon_exp_units"]
  7412. ewhole = self.defaults["excellon_exp_integer"]
  7413. efract = self.defaults["excellon_exp_decimals"]
  7414. ezeros = self.defaults["excellon_exp_zeros"]
  7415. eformat = self.defaults["excellon_exp_format"]
  7416. slot_type = self.defaults["excellon_exp_slot_type"]
  7417. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7418. if fc_units == 'MM':
  7419. factor = 1 if eunits == 'METRIC' else 0.03937
  7420. else:
  7421. factor = 25.4 if eunits == 'METRIC' else 1
  7422. def make_excellon():
  7423. try:
  7424. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7425. header = 'M48\n'
  7426. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7427. (str(self.version), str(self.version_date))
  7428. header += ';Filename: %s' % str(obj_name) + '\n'
  7429. header += ';Created on : %s' % time_str + '\n'
  7430. if eformat == 'dec':
  7431. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7432. header += eunits + '\n'
  7433. for tool in obj.tools:
  7434. if eunits == 'METRIC':
  7435. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7436. tool=str(tool),
  7437. dec=2)
  7438. else:
  7439. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7440. tool=str(tool),
  7441. dec=4)
  7442. else:
  7443. if ezeros == 'LZ':
  7444. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7445. form='ndec', e_zeros='LZ', factor=factor,
  7446. slot_type=slot_type)
  7447. header += '%s,%s\n' % (eunits, 'LZ')
  7448. header += format_exc
  7449. for tool in obj.tools:
  7450. if eunits == 'METRIC':
  7451. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7452. tool=str(tool),
  7453. dec=2)
  7454. else:
  7455. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7456. tool=str(tool),
  7457. dec=4)
  7458. else:
  7459. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7460. form='ndec', e_zeros='TZ', factor=factor,
  7461. slot_type=slot_type)
  7462. header += '%s,%s\n' % (eunits, 'TZ')
  7463. header += format_exc
  7464. for tool in obj.tools:
  7465. if eunits == 'METRIC':
  7466. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7467. tool=str(tool),
  7468. dec=2)
  7469. else:
  7470. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7471. tool=str(tool),
  7472. dec=4)
  7473. header += '%\n'
  7474. footer = 'M30\n'
  7475. exported_excellon = header
  7476. exported_excellon += excellon_code
  7477. exported_excellon += footer
  7478. if local_use is None:
  7479. try:
  7480. with open(filename, 'w') as fp:
  7481. fp.write(exported_excellon)
  7482. except PermissionError:
  7483. self.inform.emit('[WARNING] %s' %
  7484. _("Permission denied, saving not possible.\n"
  7485. "Most likely another app is holding the file open and not accessible."))
  7486. return 'fail'
  7487. if self.defaults["global_open_style"] is False:
  7488. self.file_opened.emit("Excellon", filename)
  7489. self.file_saved.emit("Excellon", filename)
  7490. self.inform.emit('[success] %s: %s' %
  7491. (_("Excellon file exported to"), filename))
  7492. else:
  7493. return exported_excellon
  7494. except Exception as e:
  7495. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7496. return 'fail'
  7497. if use_thread is True:
  7498. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7499. def job_thread_exc(app_obj):
  7500. ret = make_excellon()
  7501. if ret == 'fail':
  7502. self.inform.emit('[ERROR_NOTCL] %s' %
  7503. _('Could not export Excellon file.'))
  7504. return
  7505. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7506. else:
  7507. ret = make_excellon()
  7508. if ret == 'fail':
  7509. self.inform.emit('[ERROR_NOTCL] %s' %
  7510. _('Could not export Excellon file.'))
  7511. return 'fail'
  7512. if local_use is not None:
  7513. return ret
  7514. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7515. """
  7516. Exports a Gerber Object to an Gerber file.
  7517. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7518. :param filename: Path to the Gerber file to save to.
  7519. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7520. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7521. :param use_thread: if to be run in a separate thread
  7522. :return:
  7523. """
  7524. self.report_usage("export_gerber()")
  7525. if filename is None:
  7526. filename = self.defaults["global_last_save_folder"]
  7527. self.log.debug("export_gerber()")
  7528. if local_use is None:
  7529. try:
  7530. obj = self.collection.get_by_name(str(obj_name))
  7531. except:
  7532. # TODO: The return behavior has not been established... should raise exception?
  7533. return "Could not retrieve object: %s" % obj_name
  7534. else:
  7535. obj = local_use
  7536. # updated units
  7537. gunits = self.defaults["gerber_exp_units"]
  7538. gwhole = self.defaults["gerber_exp_integer"]
  7539. gfract = self.defaults["gerber_exp_decimals"]
  7540. gzeros = self.defaults["gerber_exp_zeros"]
  7541. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7542. if fc_units == 'MM':
  7543. factor = 1 if gunits == 'MM' else 0.03937
  7544. else:
  7545. factor = 25.4 if gunits == 'MM' else 1
  7546. def make_gerber():
  7547. try:
  7548. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7549. header = 'G04*\n'
  7550. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7551. (str(self.version), str(self.version_date))
  7552. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7553. header += 'G04 Created on : %s*' % time_str + '\n'
  7554. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7555. header += "%MO{units}*%\n".format(units=gunits)
  7556. for apid in obj.apertures:
  7557. if obj.apertures[apid]['type'] == 'C':
  7558. header += "%ADD{apid}{type},{size}*%\n".format(
  7559. apid=str(apid),
  7560. type='C',
  7561. size=(factor * obj.apertures[apid]['size'])
  7562. )
  7563. elif obj.apertures[apid]['type'] == 'R':
  7564. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7565. apid=str(apid),
  7566. type='R',
  7567. width=(factor * obj.apertures[apid]['width']),
  7568. height=(factor * obj.apertures[apid]['height'])
  7569. )
  7570. elif obj.apertures[apid]['type'] == 'O':
  7571. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7572. apid=str(apid),
  7573. type='O',
  7574. width=(factor * obj.apertures[apid]['width']),
  7575. height=(factor * obj.apertures[apid]['height'])
  7576. )
  7577. header += '\n'
  7578. # obsolete units but some software may need it
  7579. if gunits == 'IN':
  7580. header += 'G70*\n'
  7581. else:
  7582. header += 'G71*\n'
  7583. # Absolute Mode
  7584. header += 'G90*\n'
  7585. header += 'G01*\n'
  7586. # positive polarity
  7587. header += '%LPD*%\n'
  7588. footer = 'M02*\n'
  7589. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7590. exported_gerber = header
  7591. exported_gerber += gerber_code
  7592. exported_gerber += footer
  7593. if local_use is None:
  7594. try:
  7595. with open(filename, 'w') as fp:
  7596. fp.write(exported_gerber)
  7597. except PermissionError:
  7598. self.inform.emit('[WARNING] %s' %
  7599. _("Permission denied, saving not possible.\n"
  7600. "Most likely another app is holding the file open and not accessible."))
  7601. return 'fail'
  7602. if self.defaults["global_open_style"] is False:
  7603. self.file_opened.emit("Gerber", filename)
  7604. self.file_saved.emit("Gerber", filename)
  7605. self.inform.emit('[success] %s: %s' %
  7606. (_("Gerber file exported to"), filename))
  7607. else:
  7608. return exported_gerber
  7609. except Exception as e:
  7610. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7611. return 'fail'
  7612. if use_thread is True:
  7613. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7614. def job_thread_grb(app_obj):
  7615. ret = make_gerber()
  7616. if ret == 'fail':
  7617. self.inform.emit('[ERROR_NOTCL] %s' %
  7618. _('Could not export Gerber file.'))
  7619. return
  7620. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7621. else:
  7622. ret = make_gerber()
  7623. if ret == 'fail':
  7624. self.inform.emit('[ERROR_NOTCL] %s' %
  7625. _('Could not export Gerber file.'))
  7626. return 'fail'
  7627. if local_use is not None:
  7628. return ret
  7629. def export_dxf(self, obj_name, filename, use_thread=True):
  7630. """
  7631. Exports a Geometry Object to an DXF file.
  7632. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7633. :param filename: Path to the DXF file to save to.
  7634. :param use_thread: if to be run in a separate thread
  7635. :return:
  7636. """
  7637. self.report_usage("export_dxf()")
  7638. if filename is None:
  7639. filename = self.defaults["global_last_save_folder"]
  7640. self.log.debug("export_dxf()")
  7641. format_exc = ''
  7642. units = ''
  7643. try:
  7644. obj = self.collection.get_by_name(str(obj_name))
  7645. except:
  7646. # TODO: The return behavior has not been established... should raise exception?
  7647. return "Could not retrieve object: %s" % obj_name
  7648. # updated units
  7649. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7650. if units == 'IN' or units == 'INCH':
  7651. units = 'INCH'
  7652. elif units == 'MM' or units == 'METIRC':
  7653. units ='METRIC'
  7654. def make_dxf():
  7655. try:
  7656. dxf_code = obj.export_dxf()
  7657. dxf_code.saveas(filename)
  7658. if self.defaults["global_open_style"] is False:
  7659. self.file_opened.emit("DXF", filename)
  7660. self.file_saved.emit("DXF", filename)
  7661. self.inform.emit('[success] %s: %s' %
  7662. (_("DXF file exported to"), filename))
  7663. except:
  7664. return 'fail'
  7665. if use_thread is True:
  7666. with self.proc_container.new(_("Exporting DXF")) as proc:
  7667. def job_thread_exc(app_obj):
  7668. ret = make_dxf()
  7669. if ret == 'fail':
  7670. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7671. _('Could not export DXF file.'))
  7672. return
  7673. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7674. else:
  7675. ret = make_dxf()
  7676. if ret == 'fail':
  7677. self.inform.emit('[WARNING_NOTCL] %s' %
  7678. _('Could not export DXF file.'))
  7679. return
  7680. def import_svg(self, filename, geo_type='geometry', outname=None):
  7681. """
  7682. Adds a new Geometry Object to the projects and populates
  7683. it with shapes extracted from the SVG file.
  7684. :param filename: Path to the SVG file.
  7685. :param outname:
  7686. :return:
  7687. """
  7688. self.report_usage("import_svg()")
  7689. obj_type = ""
  7690. if geo_type is None or geo_type == "geometry":
  7691. obj_type = "geometry"
  7692. elif geo_type == "gerber":
  7693. obj_type = geo_type
  7694. else:
  7695. self.inform.emit('[ERROR_NOTCL] %s' %
  7696. _("Not supported type is picked as parameter. "
  7697. "Only Geometry and Gerber are supported"))
  7698. return
  7699. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7700. def obj_init(geo_obj, app_obj):
  7701. geo_obj.import_svg(filename, obj_type, units=units)
  7702. geo_obj.multigeo = False
  7703. with self.proc_container.new(_("Importing SVG")) as proc:
  7704. # Object name
  7705. name = outname or filename.split('/')[-1].split('\\')[-1]
  7706. self.new_object(obj_type, name, obj_init, autoselected=False)
  7707. self.progress.emit(20)
  7708. # Register recent file
  7709. self.file_opened.emit("svg", filename)
  7710. # GUI feedback
  7711. self.inform.emit('[success] %s: %s' %
  7712. (_("Opened"), filename))
  7713. self.progress.emit(100)
  7714. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7715. """
  7716. Adds a new Geometry Object to the projects and populates
  7717. it with shapes extracted from the DXF file.
  7718. :param filename: Path to the DXF file.
  7719. :param outname:
  7720. :type putname: str
  7721. :return:
  7722. """
  7723. self.report_usage("import_dxf()")
  7724. obj_type = ""
  7725. if geo_type is None or geo_type == "geometry":
  7726. obj_type = "geometry"
  7727. elif geo_type == "gerber":
  7728. obj_type = geo_type
  7729. else:
  7730. self.inform.emit('[ERROR_NOTCL] %s' %
  7731. _("Not supported type is picked as parameter. "
  7732. "Only Geometry and Gerber are supported"))
  7733. return
  7734. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7735. def obj_init(geo_obj, app_obj):
  7736. geo_obj.import_dxf(filename, obj_type, units=units)
  7737. geo_obj.multigeo = False
  7738. with self.proc_container.new(_("Importing DXF")) as proc:
  7739. # Object name
  7740. name = outname or filename.split('/')[-1].split('\\')[-1]
  7741. self.new_object(obj_type, name, obj_init, autoselected=False)
  7742. self.progress.emit(20)
  7743. # Register recent file
  7744. self.file_opened.emit("dxf", filename)
  7745. # GUI feedback
  7746. self.inform.emit('[success] %s: %s' %
  7747. (_("Opened"), filename))
  7748. self.progress.emit(100)
  7749. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7750. """
  7751. Adds a new Geometry Object to the projects and populates
  7752. it with shapes extracted from the SVG file.
  7753. :param filename: Path to the SVG file.
  7754. :param o_type: type of FlatCAM objeect
  7755. :param dpi: dot per inch
  7756. :param mode: black or color
  7757. :param mask: dictate the level of detail
  7758. :param outname: name for the resulting file
  7759. :return:
  7760. """
  7761. self.report_usage("import_image()")
  7762. if o_type is None or o_type == "geometry":
  7763. obj_type = "geometry"
  7764. elif o_type == "gerber":
  7765. obj_type = o_type
  7766. else:
  7767. self.inform.emit('[ERROR_NOTCL] %s' %
  7768. _("Not supported type is picked as parameter. "
  7769. "Only Geometry and Gerber are supported"))
  7770. return
  7771. def obj_init(geo_obj, app_obj):
  7772. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7773. geo_obj.multigeo = False
  7774. with self.proc_container.new(_("Importing Image")) as proc:
  7775. # Object name
  7776. name = outname or filename.split('/')[-1].split('\\')[-1]
  7777. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7778. self.new_object(obj_type, name, obj_init)
  7779. self.progress.emit(20)
  7780. # Register recent file
  7781. self.file_opened.emit("image", filename)
  7782. # GUI feedback
  7783. self.inform.emit('[success] %s: %s' %
  7784. (_("Opened"), filename))
  7785. self.progress.emit(100)
  7786. def open_gerber(self, filename, outname=None):
  7787. """
  7788. Opens a Gerber file, parses it and creates a new object for
  7789. it in the program. Thread-safe.
  7790. :param outname: Name of the resulting object. None causes the
  7791. name to be that of the file.
  7792. :param filename: Gerber file filename
  7793. :type filename: str
  7794. :param follow: If true, the parser will not create polygons, just lines
  7795. following the gerber path.
  7796. :type follow: bool
  7797. :return: None
  7798. """
  7799. # How the object should be initialized
  7800. def obj_init(gerber_obj, app_obj):
  7801. assert isinstance(gerber_obj, FlatCAMGerber), \
  7802. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7803. # Opening the file happens here
  7804. self.progress.emit(30)
  7805. try:
  7806. gerber_obj.parse_file(filename)
  7807. except IOError:
  7808. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7809. (_("Failed to open file"), filename))
  7810. app_obj.progress.emit(0)
  7811. return "fail"
  7812. except ParseError as err:
  7813. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7814. (_("Failed to parse file"), filename, str(err)))
  7815. app_obj.progress.emit(0)
  7816. self.log.error(str(err))
  7817. return "fail"
  7818. except Exception as e:
  7819. log.debug("App.open_gerber() --> %s" % str(e))
  7820. msg = '[ERROR] %s' % \
  7821. _("An internal error has occurred. See shell.\n")
  7822. msg += traceback.format_exc()
  7823. app_obj.inform.emit(msg)
  7824. return "fail"
  7825. if gerber_obj.is_empty():
  7826. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7827. # self.collection.set_active(gerber_obj.options["name"])
  7828. # self.collection.delete_active()
  7829. self.inform.emit('[ERROR_NOTCL] %s' %
  7830. _("Object is not Gerber file or empty. Aborting object creation."))
  7831. return "fail"
  7832. # Further parsing
  7833. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7834. App.log.debug("open_gerber()")
  7835. with self.proc_container.new(_("Opening Gerber")) as proc:
  7836. self.progress.emit(10)
  7837. # Object name
  7838. name = outname or filename.split('/')[-1].split('\\')[-1]
  7839. # # ## Object creation # ##
  7840. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7841. if ret == 'fail':
  7842. self.inform.emit('[ERROR_NOTCL]%s' %
  7843. _(' Open Gerber failed. Probable not a Gerber file.'))
  7844. return
  7845. # Register recent file
  7846. self.file_opened.emit("gerber", filename)
  7847. self.progress.emit(100)
  7848. # GUI feedback
  7849. self.inform.emit('[success] %s: %s' %
  7850. (_("Opened"), filename))
  7851. def open_excellon(self, filename, outname=None, plot=True):
  7852. """
  7853. Opens an Excellon file, parses it and creates a new object for
  7854. it in the program. Thread-safe.
  7855. :param outname: Name of the resulting object. None causes the
  7856. name to be that of the file.
  7857. :param filename: Excellon file filename
  7858. :type filename: str
  7859. :return: None
  7860. """
  7861. App.log.debug("open_excellon()")
  7862. # How the object should be initialized
  7863. def obj_init(excellon_obj, app_obj):
  7864. # self.progress.emit(20)
  7865. try:
  7866. ret = excellon_obj.parse_file(filename=filename)
  7867. if ret == "fail":
  7868. log.debug("Excellon parsing failed.")
  7869. self.inform.emit('[ERROR_NOTCL] %s' %
  7870. _("This is not Excellon file."))
  7871. return "fail"
  7872. except IOError:
  7873. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7874. (_("Cannot open file"), filename))
  7875. log.debug("Could not open Excellon object.")
  7876. self.progress.emit(0) # TODO: self and app_bjj mixed
  7877. return "fail"
  7878. except:
  7879. msg = '[ERROR_NOTCL] %s' % \
  7880. _("An internal error has occurred. See shell.\n")
  7881. msg += traceback.format_exc()
  7882. app_obj.inform.emit(msg)
  7883. return "fail"
  7884. ret = excellon_obj.create_geometry()
  7885. if ret == 'fail':
  7886. log.debug("Could not create geometry for Excellon object.")
  7887. return "fail"
  7888. for tool in excellon_obj.tools:
  7889. if excellon_obj.tools[tool]['solid_geometry']:
  7890. return
  7891. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7892. (_("No geometry found in file"), filename))
  7893. return "fail"
  7894. with self.proc_container.new(_("Opening Excellon.")):
  7895. # Object name
  7896. name = outname or filename.split('/')[-1].split('\\')[-1]
  7897. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7898. if ret_val == 'fail':
  7899. self.inform.emit('[ERROR_NOTCL] %s' %
  7900. _('Open Excellon file failed. Probable not an Excellon file.'))
  7901. return
  7902. # Register recent file
  7903. self.file_opened.emit("excellon", filename)
  7904. # GUI feedback
  7905. self.inform.emit('[success] %s: %s' %
  7906. (_("Opened"), filename))
  7907. def open_gcode(self, filename, outname=None, plot=True):
  7908. """
  7909. Opens a G-gcode file, parses it and creates a new object for
  7910. it in the program. Thread-safe.
  7911. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7912. :param filename: G-code file filename
  7913. :type filename: str
  7914. :return: None
  7915. """
  7916. App.log.debug("open_gcode()")
  7917. # How the object should be initialized
  7918. def obj_init(job_obj, app_obj_):
  7919. """
  7920. :param job_obj: the resulting object
  7921. :type app_obj_: App
  7922. """
  7923. assert isinstance(app_obj_, App), \
  7924. "Initializer expected App, got %s" % type(app_obj_)
  7925. self.progress.emit(10)
  7926. try:
  7927. f = open(filename)
  7928. gcode = f.read()
  7929. f.close()
  7930. except IOError:
  7931. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7932. (_("Failed to open"), filename))
  7933. self.progress.emit(0)
  7934. return "fail"
  7935. job_obj.gcode = gcode
  7936. self.progress.emit(20)
  7937. ret = job_obj.gcode_parse()
  7938. if ret == "fail":
  7939. self.inform.emit('[ERROR_NOTCL] %s' %
  7940. _("This is not GCODE"))
  7941. return "fail"
  7942. self.progress.emit(60)
  7943. job_obj.create_geometry()
  7944. with self.proc_container.new(_("Opening G-Code.")):
  7945. # Object name
  7946. name = outname or filename.split('/')[-1].split('\\')[-1]
  7947. # New object creation and file processing
  7948. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7949. if ret == 'fail':
  7950. self.inform.emit('[ERROR_NOTCL] %s' %
  7951. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  7952. "Attempting to create a FlatCAM CNCJob Object from "
  7953. "G-Code file failed during processing"))
  7954. return "fail"
  7955. # Register recent file
  7956. self.file_opened.emit("cncjob", filename)
  7957. # GUI feedback
  7958. self.inform.emit('[success] %s: %s' %
  7959. (_("Opened"), filename))
  7960. self.progress.emit(100)
  7961. def open_config_file(self, filename, run_from_arg=None):
  7962. """
  7963. Loads a config file from the specified file.
  7964. :param filename: Name of the file from which to load.
  7965. :type filename: str
  7966. :return: None
  7967. """
  7968. App.log.debug("Opening config file: " + filename)
  7969. # add the tab if it was closed
  7970. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7971. # first clear previous text in text editor (if any)
  7972. self.ui.code_editor.clear()
  7973. # Switch plot_area to CNCJob tab
  7974. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7975. try:
  7976. if filename:
  7977. f = QtCore.QFile(filename)
  7978. if f.open(QtCore.QIODevice.ReadOnly):
  7979. stream = QtCore.QTextStream(f)
  7980. gcode_edited = stream.readAll()
  7981. self.ui.code_editor.setPlainText(gcode_edited)
  7982. f.close()
  7983. except IOError:
  7984. App.log.error("Failed to open config file: %s" % filename)
  7985. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7986. (_("Failed to open config file"), filename))
  7987. return
  7988. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  7989. """
  7990. Loads a project from the specified file.
  7991. 1) Loads and parses file
  7992. 2) Registers the file as recently opened.
  7993. 3) Calls on_file_new()
  7994. 4) Updates options
  7995. 5) Calls new_object() with the object's from_dict() as init method.
  7996. 6) Calls plot_all() if plot=True
  7997. :param filename: Name of the file from which to load.
  7998. :type filename: str
  7999. :param run_from_arg: True if run for arguments
  8000. :param plot: If True plot all objects in the project
  8001. :param cli: run from command line
  8002. :return: None
  8003. """
  8004. App.log.debug("Opening project: " + filename)
  8005. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8006. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8007. if cli is None:
  8008. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8009. # Open and parse an uncompressed Project file
  8010. try:
  8011. f = open(filename, 'r')
  8012. except IOError:
  8013. App.log.error("Failed to open project file: %s" % filename)
  8014. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8015. (_("Failed to open project file"), filename))
  8016. return
  8017. try:
  8018. d = json.load(f, object_hook=dict2obj)
  8019. except Exception as e:
  8020. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8021. (filename, str(e)))
  8022. f.close()
  8023. # Open and parse a compressed Project file
  8024. try:
  8025. with lzma.open(filename) as f:
  8026. file_content = f.read().decode('utf-8')
  8027. d = json.loads(file_content, object_hook=dict2obj)
  8028. except Exception as e:
  8029. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8030. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8031. (_("Failed to open project file"), filename))
  8032. return
  8033. # Clear the current project
  8034. # # NOT THREAD SAFE # ##
  8035. if run_from_arg is True:
  8036. pass
  8037. elif cli is True:
  8038. self.delete_selection_shape()
  8039. else:
  8040. self.on_file_new()
  8041. # Project options
  8042. self.options.update(d['options'])
  8043. self.project_filename = filename
  8044. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8045. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8046. if cli is None:
  8047. self.set_screen_units(self.options["units"])
  8048. # Re create objects
  8049. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8050. for obj in d['objs']:
  8051. def obj_init(obj_inst, app_inst):
  8052. obj_inst.from_dict(obj)
  8053. App.log.debug("Recreating from opened project an %s object: %s" %
  8054. (obj['kind'].capitalize(), obj['options']['name']))
  8055. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8056. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8057. if cli is None:
  8058. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8059. obj['kind'].upper(),
  8060. obj['options']['name']
  8061. )
  8062. )
  8063. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8064. self.inform.emit('[success] %s: %s' %
  8065. (_("Project loaded from"), filename))
  8066. self.should_we_save = False
  8067. self.file_opened.emit("project", filename)
  8068. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8069. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8070. if cli is None:
  8071. self.set_ui_title(name=self.project_filename)
  8072. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8073. def propagate_defaults(self, silent=False):
  8074. """
  8075. This method is used to set default values in classes. It's
  8076. an alternative to project options but allows the use
  8077. of values invisible to the user.
  8078. :return: None
  8079. """
  8080. if silent is False:
  8081. self.log.debug("propagate_defaults()")
  8082. # Which objects to update the given parameters.
  8083. routes = {
  8084. "global_zdownrate": CNCjob,
  8085. "excellon_zeros": Excellon,
  8086. "excellon_format_upper_in": Excellon,
  8087. "excellon_format_lower_in": Excellon,
  8088. "excellon_format_upper_mm": Excellon,
  8089. "excellon_format_lower_mm": Excellon,
  8090. "excellon_units": Excellon,
  8091. "gerber_use_buffer_for_union": Gerber,
  8092. "geometry_multidepth": Geometry
  8093. }
  8094. for param in routes:
  8095. if param in routes[param].defaults:
  8096. try:
  8097. routes[param].defaults[param] = self.defaults[param]
  8098. if silent is False:
  8099. self.log.debug(" " + param + " OK")
  8100. except KeyError:
  8101. if silent is False:
  8102. self.log.debug(" ERROR: " + param + " not in defaults.")
  8103. else:
  8104. # Try extracting the name:
  8105. # classname_param here is param in the object
  8106. if param.find(routes[param].__name__.lower() + "_") == 0:
  8107. p = param[len(routes[param].__name__) + 1:]
  8108. if p in routes[param].defaults:
  8109. routes[param].defaults[p] = self.defaults[param]
  8110. if silent is False:
  8111. self.log.debug(" " + param + " OK!")
  8112. def restore_main_win_geom(self):
  8113. try:
  8114. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8115. self.defaults["global_def_win_y"],
  8116. self.defaults["global_def_win_w"],
  8117. self.defaults["global_def_win_h"])
  8118. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8119. except KeyError as e:
  8120. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8121. def plot_all(self, zoom=True):
  8122. """
  8123. Re-generates all plots from all objects.
  8124. :return: None
  8125. """
  8126. self.log.debug("Plot_all()")
  8127. for obj in self.collection.get_list():
  8128. def worker_task(obj):
  8129. with self.proc_container.new("Plotting"):
  8130. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8131. if zoom:
  8132. self.object_plotted.emit(obj)
  8133. # Send to worker
  8134. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8135. def register_folder(self, filename):
  8136. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8137. def register_save_folder(self, filename):
  8138. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8139. def set_progress_bar(self, percentage, text=""):
  8140. self.ui.progress_bar.setValue(int(percentage))
  8141. def setup_shell(self):
  8142. """
  8143. Creates shell functions. Runs once at startup.
  8144. :return: None
  8145. """
  8146. self.log.debug("setup_shell()")
  8147. def shelp(p=None):
  8148. if not p:
  8149. return _("Available commands:\n") + \
  8150. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8151. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8152. if p not in commands:
  8153. return "Unknown command: %s" % p
  8154. return commands[p]["help"]
  8155. # --- Migrated to new architecture ---
  8156. # def options(name):
  8157. # ops = self.collection.get_by_name(str(name)).options
  8158. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8159. def h(*args):
  8160. """
  8161. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8162. and standalone parameters into list.
  8163. """
  8164. kwa = {}
  8165. a = []
  8166. n = len(args)
  8167. name = None
  8168. for i in range(n):
  8169. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8170. if match:
  8171. assert name is None
  8172. name = match.group(1)
  8173. continue
  8174. if name is None:
  8175. a.append(args[i])
  8176. else:
  8177. kwa[name] = args[i]
  8178. name = None
  8179. return a, kwa
  8180. @contextmanager
  8181. def wait_signal(signal, timeout=10000):
  8182. """
  8183. Block loop until signal emitted, timeout (ms) elapses
  8184. or unhandled exception happens in a thread.
  8185. :param timeout: time after which the loop is exited
  8186. :param signal: Signal to wait for.
  8187. """
  8188. loop = QtCore.QEventLoop()
  8189. # Normal termination
  8190. signal.connect(loop.quit)
  8191. # Termination by exception in thread
  8192. self.thread_exception.connect(loop.quit)
  8193. status = {'timed_out': False}
  8194. def report_quit():
  8195. status['timed_out'] = True
  8196. loop.quit()
  8197. yield
  8198. # Temporarily change how exceptions are managed.
  8199. oeh = sys.excepthook
  8200. ex = []
  8201. def except_hook(type_, value, traceback_):
  8202. ex.append(value)
  8203. oeh(type_, value, traceback_)
  8204. sys.excepthook = except_hook
  8205. # Terminate on timeout
  8206. if timeout is not None:
  8207. QtCore.QTimer.singleShot(timeout, report_quit)
  8208. # # ## Block ## ##
  8209. loop.exec_()
  8210. # Restore exception management
  8211. sys.excepthook = oeh
  8212. if ex:
  8213. self.raiseTclError(str(ex[0]))
  8214. if status['timed_out']:
  8215. raise Exception('Timed out!')
  8216. def make_docs():
  8217. output = ''
  8218. import collections
  8219. od = collections.OrderedDict(sorted(commands.items()))
  8220. for cmd_, val in od.items():
  8221. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8222. t = val['help']
  8223. usage_i = t.find('>')
  8224. if usage_i < 0:
  8225. expl = t
  8226. output += expl + '\n\n'
  8227. continue
  8228. expl = t[:usage_i - 1]
  8229. output += expl + '\n\n'
  8230. end_usage_i = t[usage_i:].find('\n')
  8231. if end_usage_i < 0:
  8232. end_usage_i = len(t[usage_i:])
  8233. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8234. else:
  8235. extras = t[usage_i+end_usage_i+1:]
  8236. parts = [s.strip() for s in extras.split('\n')]
  8237. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8238. for p in parts:
  8239. output += ' ' + p + '\n\n'
  8240. return output
  8241. '''
  8242. Howto implement TCL shell commands:
  8243. All parameters passed to command should be possible to set as None and test it afterwards.
  8244. This is because we need to see error caused in tcl,
  8245. if None value as default parameter is not allowed TCL will return empty error.
  8246. Use:
  8247. def mycommand(name=None,...):
  8248. Test it like this:
  8249. if name is None:
  8250. self.raise_tcl_error('Argument name is missing.')
  8251. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8252. otherwise we will miss it and processing will silently continue.
  8253. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8254. which is catched in exec_command and displayed in TCL shell console with red background.
  8255. Error in console is displayed with TCL trace.
  8256. This behavior works only within main thread,
  8257. errors with promissed tasks can be catched and detected only with log.
  8258. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8259. TCL shell.
  8260. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8261. '''
  8262. commands = {
  8263. 'help': {
  8264. 'fcn': shelp,
  8265. 'help': _("Shows list of commands.")
  8266. },
  8267. }
  8268. # Import/overwrite tcl commands as objects of TclCommand descendants
  8269. # This modifies the variable 'commands'.
  8270. tclCommands.register_all_commands(self, commands)
  8271. # Add commands to the tcl interpreter
  8272. for cmd in commands:
  8273. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8274. # Make the tcl puts function return instead of print to stdout
  8275. self.tcl.eval('''
  8276. rename puts original_puts
  8277. proc puts {args} {
  8278. if {[llength $args] == 1} {
  8279. return "[lindex $args 0]"
  8280. } else {
  8281. eval original_puts $args
  8282. }
  8283. }
  8284. ''')
  8285. def setup_recent_items(self):
  8286. # TODO: Move this to constructor
  8287. icons = {
  8288. "gerber": "share/flatcam_icon16.png",
  8289. "excellon": "share/drill16.png",
  8290. 'geometry': "share/geometry16.png",
  8291. "cncjob": "share/cnc16.png",
  8292. "project": "share/project16.png",
  8293. "svg": "share/geometry16.png",
  8294. "dxf": "share/dxf16.png",
  8295. "pdf": "share/pdf32.png",
  8296. "image": "share/image16.png"
  8297. }
  8298. openers = {
  8299. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8300. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8301. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8302. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8303. 'project': self.open_project,
  8304. 'svg': self.import_svg,
  8305. 'dxf': self.import_dxf,
  8306. 'image': self.import_image,
  8307. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8308. }
  8309. # Open recent file for files
  8310. try:
  8311. f = open(self.data_path + '/recent.json')
  8312. except IOError:
  8313. App.log.error("Failed to load recent item list.")
  8314. self.inform.emit('[ERROR_NOTCL] %s' %
  8315. _("Failed to load recent item list."))
  8316. return
  8317. try:
  8318. self.recent = json.load(f)
  8319. except json.scanner.JSONDecodeError:
  8320. App.log.error("Failed to parse recent item list.")
  8321. self.inform.emit('[ERROR_NOTCL] %s' %
  8322. _("Failed to parse recent item list."))
  8323. f.close()
  8324. return
  8325. f.close()
  8326. # Open recent file for projects
  8327. try:
  8328. fp = open(self.data_path + '/recent_projects.json')
  8329. except IOError:
  8330. App.log.error("Failed to load recent project item list.")
  8331. self.inform.emit('[ERROR_NOTCL] %s' %
  8332. _("Failed to load recent projects item list."))
  8333. return
  8334. try:
  8335. self.recent_projects = json.load(fp)
  8336. except json.scanner.JSONDecodeError:
  8337. App.log.error("Failed to parse recent project item list.")
  8338. self.inform.emit('[ERROR_NOTCL] %s' %
  8339. _("Failed to parse recent project item list."))
  8340. fp.close()
  8341. return
  8342. fp.close()
  8343. # Closure needed to create callbacks in a loop.
  8344. # Otherwise late binding occurs.
  8345. def make_callback(func, fname):
  8346. def opener():
  8347. func(fname)
  8348. return opener
  8349. def reset_recent_files():
  8350. # Reset menu
  8351. self.ui.recent.clear()
  8352. self.recent = []
  8353. try:
  8354. f = open(self.data_path + '/recent.json', 'w')
  8355. except IOError:
  8356. App.log.error("Failed to open recent items file for writing.")
  8357. return
  8358. json.dump(self.recent, f)
  8359. def reset_recent_projects():
  8360. # Reset menu
  8361. self.ui.recent_projects.clear()
  8362. self.recent_projects = []
  8363. try:
  8364. fp = open(self.data_path + '/recent_projects.json', 'w')
  8365. except IOError:
  8366. App.log.error("Failed to open recent projects items file for writing.")
  8367. return
  8368. json.dump(self.recent, fp)
  8369. # Reset menu
  8370. self.ui.recent.clear()
  8371. self.ui.recent_projects.clear()
  8372. # Create menu items for projects
  8373. for recent in self.recent_projects:
  8374. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8375. if recent['kind'] == 'project':
  8376. try:
  8377. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8378. # Attach callback
  8379. o = make_callback(openers[recent["kind"]], recent['filename'])
  8380. action.triggered.connect(o)
  8381. self.ui.recent_projects.addAction(action)
  8382. except KeyError:
  8383. App.log.error("Unsupported file type: %s" % recent["kind"])
  8384. # Last action in Recent Files menu is one that Clear the content
  8385. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8386. clear_action_proj.triggered.connect(reset_recent_projects)
  8387. self.ui.recent_projects.addSeparator()
  8388. self.ui.recent_projects.addAction(clear_action_proj)
  8389. # Create menu items for files
  8390. for recent in self.recent:
  8391. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8392. if recent['kind'] != 'project':
  8393. try:
  8394. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8395. # Attach callback
  8396. o = make_callback(openers[recent["kind"]], recent['filename'])
  8397. action.triggered.connect(o)
  8398. self.ui.recent.addAction(action)
  8399. except KeyError:
  8400. App.log.error("Unsupported file type: %s" % recent["kind"])
  8401. # Last action in Recent Files menu is one that Clear the content
  8402. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8403. clear_action.triggered.connect(reset_recent_files)
  8404. self.ui.recent.addSeparator()
  8405. self.ui.recent.addAction(clear_action)
  8406. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8407. # self.ui.menufilerecent.set_submenu(recent_menu)
  8408. # recent_menu.show_all()
  8409. # self.ui.recent.show()
  8410. self.log.debug("Recent items list has been populated.")
  8411. def setup_component_editor(self):
  8412. # label = QtWidgets.QLabel("Choose an item from Project")
  8413. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8414. sel_title = QtWidgets.QTextEdit(
  8415. _('<b>Shortcut Key List</b>'))
  8416. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8417. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8418. settings = QSettings("Open Source", "FlatCAM")
  8419. if settings.contains("notebook_font_size"):
  8420. fsize = settings.value('notebook_font_size', type=int)
  8421. else:
  8422. fsize = 12
  8423. tsize = fsize + int(fsize / 2)
  8424. # selected_text = (_('''
  8425. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8426. #
  8427. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8428. # The normal flow when working in FlatCAM is the following:</span></p>
  8429. #
  8430. # <ol>
  8431. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8432. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8433. # even dragging and dropping the files on the GUI.<br />
  8434. # <br />
  8435. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8436. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8437. # &nbsp;</li>
  8438. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8439. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8440. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8441. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8442. # <br />
  8443. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8444. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8445. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8446. # it even if it was out of focus.<br />
  8447. # <br />
  8448. # You can change the parameters in this screen and the flow direction is like this:<br />
  8449. # <br />
  8450. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8451. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8452. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8453. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8454. # </ol>
  8455. #
  8456. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8457. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8458. # <strong>F3</strong>.</span></p>
  8459. #
  8460. # ''').format(fsize=fsize, tsize=tsize))
  8461. selected_text = '''
  8462. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8463. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8464. %s:</span></p>
  8465. <ol>
  8466. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8467. <br />
  8468. %s &amp; %s.</span><br />
  8469. &nbsp;</li>
  8470. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8471. <br />
  8472. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8473. <br />
  8474. %s:<br />
  8475. <br />
  8476. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8477. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8478. </ol>
  8479. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8480. <strong>F3</strong>.</span></p>
  8481. ''' % (
  8482. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8483. _("The normal flow when working in FlatCAM is the following"),
  8484. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8485. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8486. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8487. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8488. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8489. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8490. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8491. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8492. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8493. _("SELECTED TAB"),
  8494. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8495. "double clicking on the object on the canvas will bring the"),
  8496. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8497. _("You can change the parameters in this screen and the flow direction is like this"),
  8498. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8499. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8500. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8501. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8502. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8503. )
  8504. sel_title.setText(selected_text)
  8505. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8506. self.ui.selected_scroll_area.setWidget(sel_title)
  8507. def setup_obj_classes(self):
  8508. """
  8509. Sets up application specifics on the FlatCAMObj class.
  8510. :return: None
  8511. """
  8512. FlatCAMObj.app = self
  8513. ObjectCollection.app = self
  8514. Gerber.app = self
  8515. Excellon.app = self
  8516. Geometry.app = self
  8517. CNCjob.app = self
  8518. FCProcess.app = self
  8519. FCProcessContainer.app = self
  8520. def version_check(self):
  8521. """
  8522. Checks for the latest version of the program. Alerts the
  8523. user if theirs is outdated. This method is meant to be run
  8524. in a separate thread.
  8525. :return: None
  8526. """
  8527. self.log.debug("version_check()")
  8528. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8529. full_url = App.version_url + \
  8530. "?s=" + str(self.defaults['global_serial']) + \
  8531. "&v=" + str(self.version) + \
  8532. "&os=" + str(self.os) + \
  8533. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8534. else:
  8535. # no_stats dict; just so it won't break things on website
  8536. no_ststs_dict = {}
  8537. no_ststs_dict["global_ststs"] = {}
  8538. full_url = App.version_url + \
  8539. "?s=" + str(self.defaults['global_serial']) + \
  8540. "&v=" + str(self.version) + \
  8541. "&os=" + str(self.os) + \
  8542. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8543. App.log.debug("Checking for updates @ %s" % full_url)
  8544. # ## Get the data
  8545. try:
  8546. f = urllib.request.urlopen(full_url)
  8547. except:
  8548. # App.log.warning("Failed checking for latest version. Could not connect.")
  8549. self.log.warning("Failed checking for latest version. Could not connect.")
  8550. self.inform.emit('[WARNING_NOTCL] %s' %
  8551. _("Failed checking for latest version. Could not connect."))
  8552. return
  8553. try:
  8554. data = json.load(f)
  8555. except Exception as e:
  8556. App.log.error("Could not parse information about latest version.")
  8557. self.inform.emit('[ERROR_NOTCL] %s' %
  8558. _("Could not parse information about latest version."))
  8559. App.log.debug("json.load(): %s" % str(e))
  8560. f.close()
  8561. return
  8562. f.close()
  8563. # ## Latest version?
  8564. if self.version >= data["version"]:
  8565. App.log.debug("FlatCAM is up to date!")
  8566. self.inform.emit('[success] %s' %
  8567. _("FlatCAM is up to date!"))
  8568. return
  8569. App.log.debug("Newer version available.")
  8570. self.message.emit(
  8571. _("Newer Version Available"),
  8572. _("There is a newer version of FlatCAM available for download:\n\n") +
  8573. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8574. _("info")
  8575. )
  8576. def on_plotcanvas_setup(self, container=None):
  8577. """
  8578. This is doing the setup for the plot area (VisPy canvas)
  8579. :param container: widget where to install the canvas
  8580. :return: None
  8581. """
  8582. if container:
  8583. plot_container = container
  8584. else:
  8585. plot_container = self.ui.right_layout
  8586. self.plotcanvas = PlotCanvas(plot_container, self)
  8587. # So it can receive key presses
  8588. self.plotcanvas.native.setFocus()
  8589. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8590. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8591. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8592. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8593. # Keys over plot enabled
  8594. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8595. self.app_cursor = self.plotcanvas.new_cursor()
  8596. self.app_cursor.enabled = False
  8597. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8598. def on_zoom_fit(self, event):
  8599. """
  8600. Callback for zoom-out request. This can be either from the corresponding
  8601. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8602. with axes limits from the geometry bounds of all objects.
  8603. :param event: Ignored.
  8604. :return: None
  8605. """
  8606. self.plotcanvas.fit_view()
  8607. def on_zoom_in(self):
  8608. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8609. def on_zoom_out(self):
  8610. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8611. def disable_all_plots(self):
  8612. self.report_usage("disable_all_plots()")
  8613. self.disable_plots(self.collection.get_list())
  8614. self.inform.emit('[success] %s' %
  8615. _("All plots disabled."))
  8616. def disable_other_plots(self):
  8617. self.report_usage("disable_other_plots()")
  8618. self.disable_plots(self.collection.get_non_selected())
  8619. self.inform.emit('[success] %s' %
  8620. _("All non selected plots disabled."))
  8621. def enable_all_plots(self):
  8622. self.report_usage("enable_all_plots()")
  8623. self.enable_plots(self.collection.get_list())
  8624. self.inform.emit('[success] %s' %
  8625. _("All plots enabled."))
  8626. def on_enable_sel_plots(self):
  8627. log.debug("App.on_enable_sel_plot()")
  8628. object_list = self.collection.get_selected()
  8629. self.enable_plots(objects=object_list)
  8630. self.inform.emit('[success] %s' %
  8631. _("Selected plots enabled..."))
  8632. def on_disable_sel_plots(self):
  8633. log.debug("App.on_disable_sel_plot()")
  8634. # self.inform.emit(_("Disabling plots ..."))
  8635. object_list = self.collection.get_selected()
  8636. self.disable_plots(objects=object_list)
  8637. self.inform.emit('[success] %s' %
  8638. _("Selected plots disabled..."))
  8639. def enable_plots(self, objects):
  8640. """
  8641. Disables plots
  8642. :param objects: list of Objects to be enabled
  8643. :return:
  8644. """
  8645. log.debug("Enabling plots ...")
  8646. # self.inform.emit(_("Working ..."))
  8647. for obj in objects:
  8648. if obj.options['plot'] is False:
  8649. obj.options.set_change_callback(lambda x: None)
  8650. obj.options['plot'] = True
  8651. obj.options.set_change_callback(obj.on_options_change)
  8652. def worker_task(objects):
  8653. with self.proc_container.new(_("Enabling plots ...")):
  8654. for obj in objects:
  8655. # obj.options['plot'] = True
  8656. if isinstance(obj, FlatCAMCNCjob):
  8657. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8658. else:
  8659. obj.plot(visible=True)
  8660. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8661. # self.plots_updated.emit()
  8662. def disable_plots(self, objects):
  8663. """
  8664. Disables plots
  8665. :param objects: list of Objects to be disabled
  8666. :return:
  8667. """
  8668. # if no objects selected then do nothing
  8669. if not self.collection.get_selected():
  8670. return
  8671. log.debug("Disabling plots ...")
  8672. # self.inform.emit(_("Working ..."))
  8673. for obj in objects:
  8674. if obj.options['plot'] is True:
  8675. obj.options.set_change_callback(lambda x: None)
  8676. obj.options['plot'] = False
  8677. obj.options.set_change_callback(obj.on_options_change)
  8678. try:
  8679. self.delete_selection_shape()
  8680. except Exception as e:
  8681. log.debug("App.disable_plots() --> %s" % str(e))
  8682. # self.plots_updated.emit()
  8683. def worker_task(objects):
  8684. with self.proc_container.new(_("Disabling plots ...")):
  8685. for obj in objects:
  8686. # obj.options['plot'] = True
  8687. if isinstance(obj, FlatCAMCNCjob):
  8688. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8689. else:
  8690. obj.plot(visible=False)
  8691. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8692. def toggle_plots(self, objects):
  8693. """
  8694. Toggle plots visibility
  8695. :param objects: list of Objects for which to be toggled the visibility
  8696. :return:
  8697. """
  8698. # if no objects selected then do nothing
  8699. if not self.collection.get_selected():
  8700. return
  8701. log.debug("Toggling plots ...")
  8702. self.inform.emit(_("Working ..."))
  8703. for obj in objects:
  8704. if obj.options['plot'] is False:
  8705. obj.options['plot'] = True
  8706. else:
  8707. obj.options['plot'] = False
  8708. self.plots_updated.emit()
  8709. def clear_plots(self):
  8710. objects = self.collection.get_list()
  8711. for obj in objects:
  8712. obj.clear(obj == objects[-1])
  8713. # Clear pool to free memory
  8714. self.clear_pool()
  8715. def generate_cnc_job(self, objects):
  8716. self.report_usage("generate_cnc_job()")
  8717. # for obj in objects:
  8718. # obj.generatecncjob()
  8719. for obj in objects:
  8720. obj.on_generatecnc_button_click()
  8721. def save_project(self, filename, quit_action=False):
  8722. """
  8723. Saves the current project to the specified file.
  8724. :param filename: Name of the file in which to save.
  8725. :type filename: str
  8726. :param quit_action: if the project saving will be followed by an app quit; boolean
  8727. :return: None
  8728. """
  8729. self.log.debug("save_project()")
  8730. self.save_in_progress = True
  8731. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8732. # Capture the latest changes
  8733. # Current object
  8734. try:
  8735. self.collection.get_active().read_form()
  8736. except:
  8737. self.log.debug("There was no active object")
  8738. pass
  8739. # Project options
  8740. self.options_read_form()
  8741. # Serialize the whole project
  8742. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8743. "options": self.options,
  8744. "version": self.version}
  8745. if self.defaults["global_save_compressed"] is True:
  8746. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8747. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8748. # # Write
  8749. f.write(g)
  8750. self.inform.emit('[success] %s: %s' %
  8751. (_("Project saved to"), filename))
  8752. else:
  8753. # Open file
  8754. try:
  8755. f = open(filename, 'w')
  8756. except IOError:
  8757. App.log.error("Failed to open file for saving: %s", filename)
  8758. return
  8759. # Write
  8760. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8761. f.close()
  8762. # verification of the saved project
  8763. # Open and parse
  8764. try:
  8765. saved_f = open(filename, 'r')
  8766. except IOError:
  8767. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8768. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8769. )
  8770. return
  8771. try:
  8772. saved_d = json.load(saved_f, object_hook=dict2obj)
  8773. except:
  8774. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8775. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8776. )
  8777. f.close()
  8778. return
  8779. saved_f.close()
  8780. if 'version' in saved_d:
  8781. self.inform.emit('[success] %s: %s' %
  8782. (_("Project saved to"), filename))
  8783. else:
  8784. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8785. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8786. )
  8787. settings = QSettings("Open Source", "FlatCAM")
  8788. lock_state = self.ui.lock_action.isChecked()
  8789. settings.setValue('toolbar_lock', lock_state)
  8790. # This will write the setting to the platform specific storage.
  8791. del settings
  8792. # if quit:
  8793. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8794. # t.start()
  8795. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8796. def start_delayed_quit(self, delay, filename, should_quit=None):
  8797. """
  8798. :param delay: period of checking if project file size is more than zero; in seconds
  8799. :param filename: the name of the project file to be checked periodically for size more than zero
  8800. :param should_quit: if the task finished will be followed by an app quit; boolean
  8801. :return:
  8802. """
  8803. to_quit = should_quit
  8804. self.save_timer = QtCore.QTimer()
  8805. self.save_timer.setInterval(delay)
  8806. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8807. self.save_timer.start()
  8808. def check_project_file_size(self, filename, should_quit=None):
  8809. """
  8810. :param filename: the name of the project file to be checked periodically for size more than zero
  8811. :param should_quit: will quit the app if True; boolean
  8812. :return:
  8813. """
  8814. try:
  8815. if os.stat(filename).st_size > 0:
  8816. self.save_in_progress = False
  8817. self.save_timer.stop()
  8818. if should_quit:
  8819. self.app_quit.emit()
  8820. except Exception as e:
  8821. traceback.print_exc()
  8822. def on_options_app2project(self):
  8823. """
  8824. Callback for Options->Transfer Options->App=>Project. Copies options
  8825. from application defaults to project defaults.
  8826. :return: None
  8827. """
  8828. self.report_usage("on_options_app2project")
  8829. self.defaults_read_form()
  8830. self.options.update(self.defaults)
  8831. self.options_write_form()
  8832. def on_options_project2app(self):
  8833. """
  8834. Callback for Options->Transfer Options->Project=>App. Copies options
  8835. from project defaults to application defaults.
  8836. :return: None
  8837. """
  8838. self.report_usage("on_options_project2app")
  8839. self.options_read_form()
  8840. self.defaults.update(self.options)
  8841. self.defaults_write_form()
  8842. def on_options_project2object(self):
  8843. """
  8844. Callback for Options->Transfer Options->Project=>Object. Copies options
  8845. from project defaults to the currently selected object.
  8846. :return: None
  8847. """
  8848. self.report_usage("on_options_project2object")
  8849. self.options_read_form()
  8850. obj = self.collection.get_active()
  8851. if obj is None:
  8852. self.inform.emit('[WARNING_NOTCL] %s' %
  8853. _("No object selected."))
  8854. return
  8855. for option in self.options:
  8856. if option.find(obj.kind + "_") == 0:
  8857. oname = option[len(obj.kind) + 1:]
  8858. obj.options[oname] = self.options[option]
  8859. obj.to_form() # Update UI
  8860. def on_options_object2project(self):
  8861. """
  8862. Callback for Options->Transfer Options->Object=>Project. Copies options
  8863. from the currently selected object to project defaults.
  8864. :return: None
  8865. """
  8866. self.report_usage("on_options_object2project")
  8867. obj = self.collection.get_active()
  8868. if obj is None:
  8869. self.inform.emit('[WARNING_NOTCL] %s' %
  8870. _("No object selected."))
  8871. return
  8872. obj.read_form()
  8873. for option in obj.options:
  8874. if option in ['name']: # TODO: Handle this better...
  8875. continue
  8876. self.options[obj.kind + "_" + option] = obj.options[option]
  8877. self.options_write_form()
  8878. def on_options_object2app(self):
  8879. """
  8880. Callback for Options->Transfer Options->Object=>App. Copies options
  8881. from the currently selected object to application defaults.
  8882. :return: None
  8883. """
  8884. self.report_usage("on_options_object2app")
  8885. obj = self.collection.get_active()
  8886. if obj is None:
  8887. self.inform.emit('[WARNING_NOTCL] %s' %
  8888. _("No object selected."))
  8889. return
  8890. obj.read_form()
  8891. for option in obj.options:
  8892. if option in ['name']: # TODO: Handle this better...
  8893. continue
  8894. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8895. self.defaults_write_form()
  8896. def on_options_app2object(self):
  8897. """
  8898. Callback for Options->Transfer Options->App=>Object. Copies options
  8899. from application defaults to the currently selected object.
  8900. :return: None
  8901. """
  8902. self.report_usage("on_options_app2object")
  8903. self.defaults_read_form()
  8904. obj = self.collection.get_active()
  8905. if obj is None:
  8906. self.inform.emit('[WARNING_NOTCL] %s' %
  8907. _("No object selected."))
  8908. return
  8909. for option in self.defaults:
  8910. if option.find(obj.kind + "_") == 0:
  8911. oname = option[len(obj.kind) + 1:]
  8912. obj.options[oname] = self.defaults[option]
  8913. obj.to_form() # Update UI
  8914. class ArgsThread(QtCore.QObject):
  8915. open_signal = pyqtSignal(list)
  8916. start = pyqtSignal()
  8917. if sys.platform == 'win32':
  8918. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8919. else:
  8920. address = ('/tmp/testipc', 'AF_UNIX')
  8921. def __init__(self):
  8922. super(ArgsThread, self).__init__()
  8923. self.start.connect(self.run)
  8924. def my_loop(self, address):
  8925. try:
  8926. listener = Listener(*address)
  8927. while True:
  8928. conn = listener.accept()
  8929. self.serve(conn)
  8930. except socket.error as e:
  8931. conn = Client(*address)
  8932. conn.send(sys.argv)
  8933. conn.send('close')
  8934. # close the current instance only if there are args
  8935. if len(sys.argv) > 1:
  8936. sys.exit()
  8937. def serve(self, conn):
  8938. while True:
  8939. msg = conn.recv()
  8940. if msg == 'close':
  8941. break
  8942. self.open_signal.emit(msg)
  8943. conn.close()
  8944. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8945. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8946. @pyqtSlot()
  8947. def run(self):
  8948. self.my_loop(self.address)
  8949. class GracefulException(Exception):
  8950. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8951. def __init__(self):
  8952. super().__init__()
  8953. def __str__(self):
  8954. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8955. # end of file