FlatCAMApp.py 547 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087
  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 webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import ctypes
  22. import tkinter as tk
  23. from PyQt5 import QtPrintSupport
  24. from contextlib import contextmanager
  25. import gc
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from multiprocessing.connection import Listener, Client
  28. from multiprocessing import Pool, cpu_count
  29. import socket
  30. from array import array
  31. import vispy.scene as scene
  32. # #######################################
  33. # # Imports part of FlatCAM ##
  34. # #######################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from camlib import to_dict, dict2obj, ET, ParseError
  38. from flatcamGUI.PlotCanvas import *
  39. from flatcamGUI.PlotCanvasLegacy import *
  40. from flatcamGUI.FlatCAMGUI import *
  41. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  42. from FlatCAMPostProc import load_preprocessors
  43. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  44. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  45. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  46. from flatcamEditors.FlatCAMTextEditor import TextEditor
  47. from FlatCAMProcess import *
  48. from FlatCAMWorkerStack import WorkerStack
  49. # from flatcamGUI.VisPyVisuals import Color
  50. from vispy.gloo.util import _screenshot
  51. from vispy.io import write_png
  52. from flatcamTools import *
  53. import tclCommands
  54. import gettext
  55. import FlatCAMTranslation as fcTranslate
  56. import builtins
  57. if sys.platform == 'win32':
  58. import winreg
  59. fcTranslate.apply_language('strings')
  60. if '_' not in builtins.__dict__:
  61. _ = gettext.gettext
  62. class App(QtCore.QObject):
  63. # ########################################
  64. # # App ###
  65. # ########################################
  66. """
  67. The main application class. The constructor starts the GUI.
  68. """
  69. # Get Cmd Line Options
  70. cmd_line_shellfile = ''
  71. cmd_line_shellvar = ''
  72. cmd_line_headless = None
  73. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  74. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  75. "FlatCam.py --headless=1"
  76. try:
  77. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  78. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  79. "shellvar=",
  80. "headless=",
  81. "multiprocessing-fork="])
  82. except getopt.GetoptError:
  83. print(cmd_line_help)
  84. sys.exit(2)
  85. for opt, arg in cmd_line_options:
  86. if opt == '-h':
  87. print(cmd_line_help)
  88. sys.exit()
  89. elif opt == '--shellfile':
  90. cmd_line_shellfile = arg
  91. elif opt == '--shellvar':
  92. cmd_line_shellvar = arg
  93. elif opt == '--headless':
  94. try:
  95. cmd_line_headless = eval(arg)
  96. except NameError:
  97. pass
  98. # ## Logging ###
  99. log = logging.getLogger('base')
  100. log.setLevel(logging.DEBUG)
  101. # log.setLevel(logging.WARNING)
  102. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  103. handler = logging.StreamHandler()
  104. handler.setFormatter(formatter)
  105. log.addHandler(handler)
  106. # ##########################################################################
  107. # ################## Version and VERSION DATE ##############################
  108. # ##########################################################################
  109. version = 8.99
  110. version_date = "2019/12/12"
  111. beta = True
  112. engine = '3D'
  113. # current date now
  114. date = str(datetime.today()).rpartition('.')[0]
  115. date = ''.join(c for c in date if c not in ':-')
  116. date = date.replace(' ', '_')
  117. # URL for update checks and statistics
  118. version_url = "http://flatcam.org/version"
  119. # App URL
  120. app_url = "http://flatcam.org"
  121. # Manual URL
  122. manual_url = "http://flatcam.org/manual/index.html"
  123. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  124. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  125. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  126. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  127. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  128. # this variable will hold the project status
  129. # if True it will mean that the project was modified and not saved
  130. should_we_save = False
  131. # flag is True if saving action has been triggered
  132. save_in_progress = False
  133. # ###########################################################################
  134. # ############################# Signals ################################
  135. # ###########################################################################
  136. # Inform the user
  137. # Handled by:
  138. # * App.info() --> Print on the status bar
  139. inform = QtCore.pyqtSignal(str)
  140. app_quit = QtCore.pyqtSignal()
  141. # General purpose background task
  142. worker_task = QtCore.pyqtSignal(dict)
  143. # File opened
  144. # Handled by:
  145. # * register_folder()
  146. # * register_recent()
  147. # Note: Setting the parameters to unicode does not seem
  148. # to have an effect. Then are received as Qstring
  149. # anyway.
  150. # File type and filename
  151. file_opened = QtCore.pyqtSignal(str, str)
  152. # File type and filename
  153. file_saved = QtCore.pyqtSignal(str, str)
  154. # Percentage of progress
  155. progress = QtCore.pyqtSignal(int)
  156. plots_updated = QtCore.pyqtSignal()
  157. # Emitted by new_object() and passes the new object as argument, plot flag.
  158. # on_object_created() adds the object to the collection, plots on appropriate flag
  159. # and emits new_object_available.
  160. object_created = QtCore.pyqtSignal(object, bool, bool)
  161. # Emitted when a object has been changed (like scaled, mirrored)
  162. object_changed = QtCore.pyqtSignal(object)
  163. # Emitted after object has been plotted.
  164. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  165. object_plotted = QtCore.pyqtSignal(object)
  166. # Emitted when a new object has been added or deleted from/to the collection
  167. object_status_changed = QtCore.pyqtSignal(object, str, str)
  168. message = QtCore.pyqtSignal(str, str, str)
  169. # Emmited when shell command is finished(one command only)
  170. shell_command_finished = QtCore.pyqtSignal(object)
  171. # Emitted when multiprocess pool has been recreated
  172. pool_recreated = QtCore.pyqtSignal(object)
  173. # Emitted when an unhandled exception happens
  174. # in the worker task.
  175. thread_exception = QtCore.pyqtSignal(object)
  176. # used to signal that there are arguments for the app
  177. args_at_startup = QtCore.pyqtSignal(list)
  178. # a reusable signal to replot a list of objects
  179. # should be disconnected after use so it can be reused
  180. replot_signal = pyqtSignal(list)
  181. def __init__(self, user_defaults=True):
  182. """
  183. Starts the application.
  184. :return: app
  185. :rtype: App
  186. """
  187. App.log.info("FlatCAM Starting...")
  188. self.main_thread = QtWidgets.QApplication.instance().thread()
  189. # ############################################################################
  190. # # ################# OS-specific ############################################
  191. # ############################################################################
  192. portable = False
  193. # Folder for user settings.
  194. if sys.platform == 'win32':
  195. # #########################################################################
  196. # Setup the listening thread for another instance launching with args #####
  197. # #########################################################################
  198. # make sure the thread is stored by using a self. otherwise it's garbage collected
  199. self.th = QtCore.QThread()
  200. self.th.start(priority=QtCore.QThread.LowestPriority)
  201. self.new_launch = ArgsThread()
  202. self.new_launch.open_signal[list].connect(self.on_startup_args)
  203. self.new_launch.moveToThread(self.th)
  204. self.new_launch.start.emit()
  205. from win32com.shell import shell, shellcon
  206. if platform.architecture()[0] == '32bit':
  207. App.log.debug("Win32!")
  208. else:
  209. App.log.debug("Win64!")
  210. # #########################################################################
  211. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  212. # #########################################################################
  213. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r'):
  216. pass
  217. except FileNotFoundError:
  218. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  219. try:
  220. with open(config_file, 'r') as f:
  221. try:
  222. for line in f:
  223. param = str(line).replace('\n', '').rpartition('=')
  224. if param[0] == 'portable':
  225. try:
  226. portable = eval(param[2])
  227. except NameError:
  228. portable = False
  229. if param[0] == 'headless':
  230. if param[2].lower() == 'true':
  231. self.cmd_line_headless = 1
  232. else:
  233. self.cmd_line_headless = None
  234. except Exception as e:
  235. log.debug('App.__init__() -->%s' % str(e))
  236. return
  237. except FileNotFoundError as e:
  238. log.debug(str(e))
  239. pass
  240. if portable is False:
  241. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  242. else:
  243. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  244. self.os = 'windows'
  245. else: # Linux/Unix/MacOS
  246. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  247. self.os = 'unix'
  248. # ##########################################################################
  249. # ################## Setup folders and files ###############################
  250. # ##########################################################################
  251. if not os.path.exists(self.data_path):
  252. os.makedirs(self.data_path)
  253. App.log.debug('Created data folder: ' + self.data_path)
  254. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  255. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  256. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  257. if not os.path.exists(self.preprocessorpaths):
  258. os.makedirs(self.preprocessorpaths)
  259. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  260. # create tools_db.FlatConfig file if there is none
  261. try:
  262. f = open(self.data_path + '/tools_db.FlatConfig')
  263. f.close()
  264. except IOError:
  265. App.log.debug('Creating empty tool_db.FlatConfig')
  266. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  267. json.dump({}, f)
  268. f.close()
  269. # create current_defaults.FlatConfig file if there is none
  270. try:
  271. f = open(self.data_path + '/current_defaults.FlatConfig')
  272. f.close()
  273. except IOError:
  274. App.log.debug('Creating empty current_defaults.FlatConfig')
  275. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  276. json.dump({}, f)
  277. f.close()
  278. # create factory_defaults.FlatConfig file if there is none
  279. try:
  280. f = open(self.data_path + '/factory_defaults.FlatConfig')
  281. f.close()
  282. except IOError:
  283. App.log.debug('Creating empty factory_defaults.FlatConfig')
  284. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  285. json.dump({}, f)
  286. f.close()
  287. # create a recent files json file if there is none
  288. try:
  289. f = open(self.data_path + '/recent.json')
  290. f.close()
  291. except IOError:
  292. App.log.debug('Creating empty recent.json')
  293. f = open(self.data_path + '/recent.json', 'w')
  294. json.dump([], f)
  295. f.close()
  296. # create a recent projects json file if there is none
  297. try:
  298. fp = open(self.data_path + '/recent_projects.json')
  299. fp.close()
  300. except IOError:
  301. App.log.debug('Creating empty recent_projects.json')
  302. fp = open(self.data_path + '/recent_projects.json', 'w')
  303. json.dump([], fp)
  304. fp.close()
  305. # Application directory. CHDIR to it. Otherwise, trying to load
  306. # GUI icons will fail as their path is relative.
  307. # This will fail under cx_freeze ...
  308. self.app_home = os.path.dirname(os.path.realpath(__file__))
  309. App.log.debug("Application path is " + self.app_home)
  310. App.log.debug("Started in " + os.getcwd())
  311. # cx_freeze workaround
  312. if os.path.isfile(self.app_home):
  313. self.app_home = os.path.dirname(self.app_home)
  314. os.chdir(self.app_home)
  315. # #################################################################################
  316. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  317. # #################################################################################
  318. self.defaults = LoudDict()
  319. self.defaults.update({
  320. # Global APP Preferences
  321. "decimals_inch": 4,
  322. "decimals_metric": 4,
  323. "version": self.version,
  324. "first_run": True,
  325. "units": "MM",
  326. "global_serial": 0,
  327. "global_stats": dict(),
  328. "global_tabs_detachable": True,
  329. "global_graphic_engine": '3D',
  330. "global_app_level": 'b',
  331. "global_portable": False,
  332. "global_language": 'English',
  333. "global_version_check": True,
  334. "global_send_stats": True,
  335. "global_pan_button": '2',
  336. "global_mselect_key": 'Control',
  337. "global_project_at_startup": False,
  338. "global_systray_icon": True,
  339. "global_project_autohide": True,
  340. "global_toggle_tooltips": True,
  341. "global_worker_number": 2,
  342. "global_tolerance": 0.005,
  343. "global_open_style": True,
  344. "global_delete_confirmation": True,
  345. "global_compression_level": 3,
  346. "global_save_compressed": True,
  347. "global_machinist_setting": False,
  348. # Global GUI Preferences
  349. "global_gridx": 1.0,
  350. "global_gridy": 1.0,
  351. "global_snap_max": 0.05,
  352. "global_workspace": False,
  353. "global_workspaceT": "A4",
  354. "global_workspace_orientation": 'p',
  355. "global_grid_context_menu": {
  356. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  357. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  358. },
  359. "global_plot_fill": '#BBF268BF',
  360. "global_plot_line": '#006E20BF',
  361. "global_sel_fill": '#a5a5ffbf',
  362. "global_sel_line": '#0000ffbf',
  363. "global_alt_sel_fill": '#BBF268BF',
  364. "global_alt_sel_line": '#006E20BF',
  365. "global_draw_color": '#FF0000',
  366. "global_sel_draw_color": '#0000FF',
  367. "global_proj_item_color": '#000000',
  368. "global_proj_item_dis_color": '#b7b7cb',
  369. "global_activity_icon": 'Ball green',
  370. "global_toolbar_view": 511,
  371. "global_background_timeout": 300000, # Default value is 5 minutes
  372. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  373. # (python trace only for unknown errors),
  374. # 1 = show trace(show trace always),
  375. # 2 = (For the future).
  376. # Persistence
  377. "global_last_folder": None,
  378. "global_last_save_folder": None,
  379. # Default window geometry
  380. "global_def_win_x": 100,
  381. "global_def_win_y": 100,
  382. "global_def_win_w": 1024,
  383. "global_def_win_h": 650,
  384. "global_def_notebook_width": 1,
  385. # Constants...
  386. "global_defaults_save_period_ms": 20000, # Time between default saves.
  387. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  388. "global_shell_at_startup": False, # Show the shell at startup.
  389. "global_recent_limit": 10, # Max. items in recent list.
  390. "global_bookmarks": dict(),
  391. "global_bookmarks_limit": 10,
  392. "fit_key": 'V',
  393. "zoom_out_key": '-',
  394. "zoom_in_key": '=',
  395. "grid_toggle_key": 'G',
  396. "global_zoom_ratio": 1.5,
  397. "global_point_clipboard_format": "(%.4f, %.4f)",
  398. "global_zdownrate": None,
  399. # General GUI Settings
  400. "global_theme": 'white',
  401. "global_hover": False,
  402. "global_selection_shape": True,
  403. "global_layout": "compact",
  404. "global_cursor_type": "small",
  405. "global_cursor_size": 20,
  406. # Gerber General
  407. "gerber_plot": True,
  408. "gerber_solid": True,
  409. "gerber_multicolored": False,
  410. "gerber_circle_steps": 64,
  411. "gerber_use_buffer_for_union": True,
  412. "gerber_def_units": 'IN',
  413. "gerber_def_zeros": 'L',
  414. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  415. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  416. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  417. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  418. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  419. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  420. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  421. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  422. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  423. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  424. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  425. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  426. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  427. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  428. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  429. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  430. "Gerber File (*.tsm);;Gerber File (*.art)"
  431. "All Files (*.*)",
  432. # Gerber Options
  433. "gerber_isotooldia": 0.1,
  434. "gerber_isopasses": 1,
  435. "gerber_isooverlap": 10,
  436. "gerber_milling_type": "cl",
  437. "gerber_combine_passes": False,
  438. "gerber_iso_scope": 'all',
  439. "gerber_noncoppermargin": 0.1,
  440. "gerber_noncopperrounded": False,
  441. "gerber_bboxmargin": 0.1,
  442. "gerber_bboxrounded": False,
  443. # Gerber Advanced Options
  444. "gerber_aperture_display": False,
  445. "gerber_aperture_scale_factor": 1.0,
  446. "gerber_aperture_buffer_factor": 0.0,
  447. "gerber_follow": False,
  448. "gerber_tool_type": 'circular',
  449. "gerber_vtipdia": 0.1,
  450. "gerber_vtipangle": 30,
  451. "gerber_vcutz": -0.05,
  452. "gerber_iso_type": "full",
  453. "gerber_buffering": "full",
  454. "gerber_simplification": False,
  455. "gerber_simp_tolerance": 0.0005,
  456. # Gerber Export
  457. "gerber_exp_units": 'IN',
  458. "gerber_exp_integer": 2,
  459. "gerber_exp_decimals": 4,
  460. "gerber_exp_zeros": 'L',
  461. # Gerber Editor
  462. "gerber_editor_sel_limit": 30,
  463. "gerber_editor_newcode": 10,
  464. "gerber_editor_newsize": 0.8,
  465. "gerber_editor_newtype": 'C',
  466. "gerber_editor_newdim": "0.5, 0.5",
  467. "gerber_editor_array_size": 5,
  468. "gerber_editor_lin_axis": 'X',
  469. "gerber_editor_lin_pitch": 0.1,
  470. "gerber_editor_lin_angle": 0.0,
  471. "gerber_editor_circ_dir": 'CW',
  472. "gerber_editor_circ_angle": 0.0,
  473. "gerber_editor_scale_f": 1.0,
  474. "gerber_editor_buff_f": 0.1,
  475. "gerber_editor_ma_low": 0.0,
  476. "gerber_editor_ma_high": 1.0,
  477. # Excellon General
  478. "excellon_plot": True,
  479. "excellon_solid": True,
  480. "excellon_format_upper_in": 2,
  481. "excellon_format_lower_in": 4,
  482. "excellon_format_upper_mm": 3,
  483. "excellon_format_lower_mm": 3,
  484. "excellon_zeros": "L",
  485. "excellon_units": "INCH",
  486. "excellon_update": True,
  487. "excellon_optimization_type": 'B',
  488. "excellon_search_time": 3,
  489. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  490. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  491. "Excellon File (*.xln);;All Files (*.*)",
  492. # Excellon Options
  493. "excellon_drillz": -1.7,
  494. "excellon_travelz": 2,
  495. "excellon_endz": 0.5,
  496. "excellon_feedrate": 300,
  497. "excellon_spindlespeed": 0,
  498. "excellon_dwell": False,
  499. "excellon_dwelltime": 1,
  500. "excellon_toolchange": False,
  501. "excellon_toolchangez": 15,
  502. "excellon_ppname_e": 'default',
  503. "excellon_tooldia": 0.8,
  504. "excellon_slot_tooldia": 1.8,
  505. "excellon_gcode_type": "drills",
  506. # Excellon Advanced Options
  507. "excellon_offset": 0.0,
  508. "excellon_toolchangexy": "0.0, 0.0",
  509. "excellon_startz": None,
  510. "excellon_feedrate_rapid": 1500,
  511. "excellon_z_pdepth": -0.02,
  512. "excellon_feedrate_probe": 75,
  513. "excellon_spindledir": 'CW',
  514. "excellon_f_plunge": False,
  515. "excellon_f_retract": False,
  516. # Excellon Export
  517. "excellon_exp_units": 'INCH',
  518. "excellon_exp_format": 'ndec',
  519. "excellon_exp_integer": 2,
  520. "excellon_exp_decimals": 4,
  521. "excellon_exp_zeros": 'LZ',
  522. "excellon_exp_slot_type": 'routing',
  523. # Excellon Editor
  524. "excellon_editor_sel_limit": 30,
  525. "excellon_editor_newdia": 1.0,
  526. "excellon_editor_array_size": 5,
  527. "excellon_editor_lin_dir": 'X',
  528. "excellon_editor_lin_pitch": 2.54,
  529. "excellon_editor_lin_angle": 0.0,
  530. "excellon_editor_circ_dir": 'CW',
  531. "excellon_editor_circ_angle": 12,
  532. # Excellon Slots
  533. "excellon_editor_slot_direction": 'X',
  534. "excellon_editor_slot_angle": 0.0,
  535. "excellon_editor_slot_length": 5.0,
  536. # Excellon Slot Array
  537. "excellon_editor_slot_array_size": 5,
  538. "excellon_editor_slot_lin_dir": 'X',
  539. "excellon_editor_slot_lin_pitch": 2.54,
  540. "excellon_editor_slot_lin_angle": 0.0,
  541. "excellon_editor_slot_circ_dir": 'CW',
  542. "excellon_editor_slot_circ_angle": 0.0,
  543. # Geometry General
  544. "geometry_plot": True,
  545. "geometry_circle_steps": 64,
  546. "geometry_cnctooldia": "2.4",
  547. # Geometry Options
  548. "geometry_cutz": -2.4,
  549. "geometry_vtipdia": 0.1,
  550. "geometry_vtipangle": 30,
  551. "geometry_multidepth": False,
  552. "geometry_depthperpass": 0.8,
  553. "geometry_travelz": 2,
  554. "geometry_toolchange": False,
  555. "geometry_toolchangez": 15.0,
  556. "geometry_endz": 15.0,
  557. "geometry_feedrate": 120,
  558. "geometry_feedrate_z": 60,
  559. "geometry_spindlespeed": 0,
  560. "geometry_dwell": False,
  561. "geometry_dwelltime": 1,
  562. "geometry_ppname_g": 'default',
  563. # Geometry Advanced Options
  564. "geometry_toolchangexy": "0.0, 0.0",
  565. "geometry_startz": None,
  566. "geometry_feedrate_rapid": 1500,
  567. "geometry_extracut": False,
  568. "geometry_extracut_length": 0.1,
  569. "geometry_z_pdepth": -0.02,
  570. "geometry_f_plunge": False,
  571. "geometry_spindledir": 'CW',
  572. "geometry_feedrate_probe": 75,
  573. "geometry_segx": 0.0,
  574. "geometry_segy": 0.0,
  575. # Geometry Editor
  576. "geometry_editor_sel_limit": 30,
  577. "geometry_editor_milling_type": "cl",
  578. # CNC Job General
  579. "cncjob_plot": True,
  580. "cncjob_plot_kind": 'all',
  581. "cncjob_annotation": True,
  582. "cncjob_tooldia": 1.0,
  583. "cncjob_coords_type": "G90",
  584. "cncjob_coords_decimals": 4,
  585. "cncjob_fr_decimals": 2,
  586. "cncjob_steps_per_circle": 64,
  587. "cncjob_footer": False,
  588. "cncjob_line_ending": False,
  589. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  590. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  591. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  592. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  593. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  594. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  595. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  596. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  597. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  598. "All Files (*.*)",
  599. # CNC Job Options
  600. "cncjob_prepend": "",
  601. "cncjob_append": "",
  602. # CNC Job Advanced Options
  603. "cncjob_toolchange_macro": "",
  604. "cncjob_toolchange_macro_enable": False,
  605. "cncjob_annotation_fontsize": 9,
  606. "cncjob_annotation_fontcolor": '#990000',
  607. # NCC Tool
  608. "tools_ncctools": "1.0, 0.5",
  609. "tools_nccorder": 'rev',
  610. "tools_nccoverlap": 40,
  611. "tools_nccmargin": 1.0,
  612. "tools_nccmethod": "seed",
  613. "tools_nccconnect": True,
  614. "tools_ncccontour": True,
  615. "tools_nccrest": False,
  616. "tools_ncc_offset_choice": False,
  617. "tools_ncc_offset_value": 0.0000,
  618. "tools_nccref": 'itself',
  619. "tools_ncc_plotting": 'normal',
  620. "tools_nccmilling_type": 'cl',
  621. "tools_ncctool_type": 'V',
  622. "tools_ncccutz": -0.05,
  623. "tools_ncctipdia": 0.1,
  624. "tools_ncctipangle": 30,
  625. "tools_nccnewdia": 1.0,
  626. # Cutout Tool
  627. "tools_cutouttooldia": 2.4,
  628. "tools_cutoutkind": "single",
  629. "tools_cutoutmargin": 0.1,
  630. "tools_cutout_z": -1.8,
  631. "tools_cutout_depthperpass": 0.6,
  632. "tools_cutout_mdepth": True,
  633. "tools_cutoutgapsize": 4,
  634. "tools_gaps_ff": "4",
  635. "tools_cutout_convexshape": False,
  636. # Paint Tool
  637. "tools_painttooldia": 0.3,
  638. "tools_paintorder": 'rev',
  639. "tools_paintoverlap": 20,
  640. "tools_paintmargin": 0.0,
  641. "tools_paintmethod": "seed",
  642. "tools_selectmethod": "all",
  643. "tools_pathconnect": True,
  644. "tools_paintcontour": True,
  645. "tools_paint_plotting": 'normal',
  646. # 2-Sided Tool
  647. "tools_2sided_mirror_axis": "X",
  648. "tools_2sided_axis_loc": "point",
  649. "tools_2sided_drilldia": 3.125,
  650. # Film Tool
  651. "tools_film_type": 'neg',
  652. "tools_film_boundary": 1.0,
  653. "tools_film_scale_stroke": 0,
  654. "tools_film_color": '#000000',
  655. "tools_film_scale_cb": False,
  656. "tools_film_scale_x_entry": 1.0,
  657. "tools_film_scale_y_entry": 1.0,
  658. "tools_film_skew_cb": False,
  659. "tools_film_skew_x_entry": 0.0,
  660. "tools_film_skew_y_entry": 0.0,
  661. "tools_film_skew_ref_radio": 'bottomleft',
  662. "tools_film_mirror_cb": False,
  663. "tools_film_mirror_axis_radio": 'none',
  664. "tools_film_file_type_radio": 'svg',
  665. "tools_film_orientation": 'p',
  666. "tools_film_pagesize": 'A4',
  667. # Panel Tool
  668. "tools_panelize_spacing_columns": 0,
  669. "tools_panelize_spacing_rows": 0,
  670. "tools_panelize_columns": 1,
  671. "tools_panelize_rows": 1,
  672. "tools_panelize_constrain": False,
  673. "tools_panelize_constrainx": 200.0,
  674. "tools_panelize_constrainy": 290.0,
  675. "tools_panelize_panel_type": 'gerber',
  676. # Calculators Tool
  677. "tools_calc_vshape_tip_dia": 0.2,
  678. "tools_calc_vshape_tip_angle": 30,
  679. "tools_calc_vshape_cut_z": 0.05,
  680. "tools_calc_electro_length": 10.0,
  681. "tools_calc_electro_width": 10.0,
  682. "tools_calc_electro_cdensity": 13.0,
  683. "tools_calc_electro_growth": 10.0,
  684. # Transform Tool
  685. "tools_transform_rotate": 90,
  686. "tools_transform_skew_x": 0.0,
  687. "tools_transform_skew_y": 0.0,
  688. "tools_transform_scale_x": 1.0,
  689. "tools_transform_scale_y": 1.0,
  690. "tools_transform_scale_link": True,
  691. "tools_transform_scale_reference": True,
  692. "tools_transform_offset_x": 0.0,
  693. "tools_transform_offset_y": 0.0,
  694. "tools_transform_mirror_reference": False,
  695. "tools_transform_mirror_point": (0, 0),
  696. # SolderPaste Tool
  697. "tools_solderpaste_tools": "1.0, 0.3",
  698. "tools_solderpaste_new": 0.3,
  699. "tools_solderpaste_z_start": 0.05,
  700. "tools_solderpaste_z_dispense": 0.1,
  701. "tools_solderpaste_z_stop": 0.05,
  702. "tools_solderpaste_z_travel": 0.1,
  703. "tools_solderpaste_z_toolchange": 1.0,
  704. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  705. "tools_solderpaste_frxy": 150,
  706. "tools_solderpaste_frz": 150,
  707. "tools_solderpaste_frz_dispense": 1.0,
  708. "tools_solderpaste_speedfwd": 300,
  709. "tools_solderpaste_dwellfwd": 1,
  710. "tools_solderpaste_speedrev": 200,
  711. "tools_solderpaste_dwellrev": 1,
  712. "tools_solderpaste_pp": 'Paste_1',
  713. # Subtract Tool
  714. "tools_sub_close_paths": True,
  715. # ###################################################################################
  716. # ################################ TOOLS 2 ##########################################
  717. # ###################################################################################
  718. # Optimal Tool
  719. "tools_opt_precision": 4,
  720. # Check Rules Tool
  721. "tools_cr_trace_size": True,
  722. "tools_cr_trace_size_val": 0.25,
  723. "tools_cr_c2c": True,
  724. "tools_cr_c2c_val": 0.25,
  725. "tools_cr_c2o": True,
  726. "tools_cr_c2o_val": 1.0,
  727. "tools_cr_s2s": True,
  728. "tools_cr_s2s_val": 0.25,
  729. "tools_cr_s2sm": True,
  730. "tools_cr_s2sm_val": 0.25,
  731. "tools_cr_s2o": True,
  732. "tools_cr_s2o_val": 1.0,
  733. "tools_cr_sm2sm": True,
  734. "tools_cr_sm2sm_val": 0.25,
  735. "tools_cr_ri": True,
  736. "tools_cr_ri_val": 0.3,
  737. "tools_cr_h2h": True,
  738. "tools_cr_h2h_val": 0.3,
  739. "tools_cr_dh": True,
  740. "tools_cr_dh_val": 0.3,
  741. # QRCode Tool
  742. "tools_qrcode_version": 1,
  743. "tools_qrcode_error": 'L',
  744. "tools_qrcode_box_size": 3,
  745. "tools_qrcode_border_size": 4,
  746. "tools_qrcode_qrdata": '',
  747. "tools_qrcode_polarity": 'pos',
  748. "tools_qrcode_rounded": 's',
  749. "tools_qrcode_fill_color": '#000000',
  750. "tools_qrcode_back_color": '#FFFFFF',
  751. "tools_qrcode_sel_limit": 330,
  752. # Copper Thieving Tool
  753. "tools_copper_thieving_clearance": 0.25,
  754. "tools_copper_thieving_margin": 1.0,
  755. "tools_copper_thieving_reference": 'itself',
  756. "tools_copper_thieving_box_type": 'rect',
  757. "tools_copper_thieving_circle_steps": 64,
  758. "tools_copper_thieving_fill_type": 'solid',
  759. "tools_copper_thieving_dots_dia": 1.0,
  760. "tools_copper_thieving_dots_spacing": 2.0,
  761. "tools_copper_thieving_squares_size": 1.0,
  762. "tools_copper_thieving_squares_spacing": 2.0,
  763. "tools_copper_thieving_lines_size": 0.25,
  764. "tools_copper_thieving_lines_spacing": 2.0,
  765. "tools_copper_thieving_rb_margin": 1.0,
  766. "tools_copper_thieving_rb_thickness": 1.0,
  767. "tools_copper_thieving_mask_clearance": 0.0,
  768. # Fiducials Tool
  769. "tools_fiducials_dia": 1.0,
  770. "tools_fiducials_margin": 1.0,
  771. "tools_fiducials_mode": 'auto',
  772. "tools_fiducials_second_pos": 'up',
  773. "tools_fiducials_type": 'circular',
  774. "tools_fiducials_line_thickness": 0.25,
  775. # Calibration Tool
  776. "tools_cal_calsource": 'object',
  777. "tools_cal_travelz": 2.0,
  778. "tools_cal_verz": 0.1,
  779. "tools_cal_zeroz": False,
  780. "tools_cal_toolchangez": 15,
  781. # Utilities
  782. # file associations
  783. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  784. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  785. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  786. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  787. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  788. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  789. # Keyword list
  790. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  791. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  792. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  793. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  794. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  795. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  796. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  797. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  798. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  799. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  800. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  801. 'z_move',
  802. "script_autocompleter": True,
  803. "script_text": "",
  804. "script_plot": True,
  805. "script_source_file": "",
  806. "document_autocompleter": False,
  807. "document_text": "",
  808. "document_plot": True,
  809. "document_source_file": "",
  810. "document_font_color": '#000000',
  811. "document_sel_color": '#0055ff',
  812. "document_font_size": 6,
  813. "document_tab_size": 80,
  814. })
  815. # ############################################################
  816. # ############### Load defaults from file ####################
  817. # ############################################################
  818. self.old_defaults_found = False
  819. if user_defaults:
  820. self.load_defaults(filename='current_defaults')
  821. if self.defaults['units'] == 'MM':
  822. self.decimals = int(self.defaults['decimals_metric'])
  823. else:
  824. self.decimals = int(self.defaults['decimals_inch'])
  825. self.current_units = self.defaults['units']
  826. # #############################################################################
  827. # ##################### CREATE MULTIPROCESSING POOL ###########################
  828. # #############################################################################
  829. self.pool = Pool(processes=cpu_count())
  830. # ##########################################################################
  831. # ################## Setting the Splash Screen #############################
  832. # ##########################################################################
  833. splash_settings = QSettings("Open Source", "FlatCAM")
  834. if splash_settings.contains("splash_screen"):
  835. show_splash = splash_settings.value("splash_screen")
  836. else:
  837. splash_settings.setValue('splash_screen', 1)
  838. # This will write the setting to the platform specific storage.
  839. del splash_settings
  840. show_splash = 1
  841. if show_splash and self.cmd_line_headless != 1:
  842. splash_pix = QtGui.QPixmap('share/splash.png')
  843. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  844. # self.splash.setMask(splash_pix.mask())
  845. # move splashscreen to the current monitor
  846. desktop = QtWidgets.QApplication.desktop()
  847. screen = desktop.screenNumber(QtGui.QCursor.pos())
  848. current_screen_center = desktop.availableGeometry(screen).center()
  849. self.splash.move(current_screen_center - self.splash.rect().center())
  850. self.splash.show()
  851. self.splash.showMessage(_("FlatCAM is initializing ..."),
  852. alignment=Qt.AlignBottom | Qt.AlignLeft,
  853. color=QtGui.QColor("gray"))
  854. else:
  855. show_splash = 0
  856. # #############################################################################
  857. # ##################### Initialize GUI ########################################
  858. # #############################################################################
  859. # FlatCAM colors used in plotting
  860. self.FC_light_green = '#BBF268BF'
  861. self.FC_dark_green = '#006E20BF'
  862. self.FC_light_blue = '#a5a5ffbf'
  863. self.FC_dark_blue = '#0000ffbf'
  864. QtCore.QObject.__init__(self)
  865. self.ui = FlatCAMGUI(self)
  866. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  867. if theme_settings.contains("theme"):
  868. theme = theme_settings.value('theme', type=str)
  869. else:
  870. theme = 'white'
  871. if theme == 'white':
  872. self.cursor_color_3D = 'black'
  873. else:
  874. self.cursor_color_3D = 'gray'
  875. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  876. self.ui.final_save.connect(self.final_save)
  877. # restore the toolbar view
  878. self.restore_toolbar_view()
  879. # restore the GUI geometry
  880. self.restore_main_win_geom()
  881. # set FlatCAM units in the Status bar
  882. self.set_screen_units(self.defaults['units'])
  883. # #############################################################################
  884. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  885. # #############################################################################
  886. # when adding entries here read the comments in the method found bellow named:
  887. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  888. self.defaults_form_fields = {
  889. # General App
  890. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  891. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  892. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  893. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  894. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  895. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  896. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  897. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  898. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  899. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  900. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  901. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  902. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  903. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  904. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  905. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  906. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  907. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  908. # General GUI Preferences
  909. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  910. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  911. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  912. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  913. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  914. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  915. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  916. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  917. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  918. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  919. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  920. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  921. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  922. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  923. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  924. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  925. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  926. # General GUI Settings
  927. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  928. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  929. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  930. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  931. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  932. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  933. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  934. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  935. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  936. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  937. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  938. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  939. # Gerber General
  940. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  941. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  942. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  943. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  944. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  945. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  946. # Gerber Options
  947. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  948. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  949. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  950. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  951. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  952. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  953. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  954. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  955. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  956. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  957. # Gerber Advanced Options
  958. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  959. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  960. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  961. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  962. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  963. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  964. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  965. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  966. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  967. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  968. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  969. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  970. # Gerber Export
  971. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  972. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  973. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  974. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  975. # Gerber Editor
  976. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  977. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  978. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  979. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  980. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  981. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  982. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  983. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  984. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  985. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  986. "gerber_editor_circ_angle":
  987. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  988. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  989. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  990. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  991. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  992. # Excellon General
  993. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  994. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  995. "excellon_format_upper_in":
  996. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  997. "excellon_format_lower_in":
  998. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  999. "excellon_format_upper_mm":
  1000. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1001. "excellon_format_lower_mm":
  1002. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1003. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1004. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1005. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1006. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1007. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1008. # Excellon Options
  1009. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1010. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1011. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1012. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1013. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1014. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1015. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1016. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1017. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1018. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1019. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1020. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1021. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1022. # Excellon Advanced Options
  1023. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1024. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1025. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1026. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1027. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1028. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1029. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1030. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1031. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1032. # Excellon Export
  1033. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1034. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1035. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1036. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1037. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1038. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1039. # Excellon Editor
  1040. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1041. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1042. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1043. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1044. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1045. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1046. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1047. "excellon_editor_circ_angle":
  1048. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1049. # Excellon Slots
  1050. "excellon_editor_slot_direction":
  1051. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1052. "excellon_editor_slot_angle":
  1053. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1054. "excellon_editor_slot_length":
  1055. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1056. # Excellon Slots
  1057. "excellon_editor_slot_array_size":
  1058. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1059. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1060. "excellon_editor_slot_lin_pitch":
  1061. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1062. "excellon_editor_slot_lin_angle":
  1063. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1064. "excellon_editor_slot_circ_dir":
  1065. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1066. "excellon_editor_slot_circ_angle":
  1067. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1068. # Geometry General
  1069. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1070. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1071. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1072. # Geometry Options
  1073. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1074. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1075. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1076. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1077. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1078. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1079. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1080. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1081. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1082. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1083. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1084. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1085. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1086. # Geometry Advanced Options
  1087. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1088. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1089. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1090. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1091. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1092. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1093. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1094. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1095. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1096. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1097. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1098. # Geometry Editor
  1099. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1100. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1101. # CNCJob General
  1102. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1103. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1104. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1105. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1106. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1107. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1108. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1109. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1110. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1111. # CNC Job Options
  1112. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1113. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1114. # CNC Job Advanced Options
  1115. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1116. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1117. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1118. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1119. # NCC Tool
  1120. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1121. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1122. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1123. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1124. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1125. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1126. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1127. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1128. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1129. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1130. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1131. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1132. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1133. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1134. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1135. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1136. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1137. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1138. # CutOut Tool
  1139. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1140. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1141. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1142. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1143. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1144. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1145. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1146. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1147. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1148. # Paint Area Tool
  1149. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1150. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1151. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1152. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1153. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1154. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1155. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1156. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1157. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1158. # 2-sided Tool
  1159. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1160. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1161. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1162. # Film Tool
  1163. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1164. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1165. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1166. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1167. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1168. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1169. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1170. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1171. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1172. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1173. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1174. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1175. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1176. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1177. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1178. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1179. # Panelize Tool
  1180. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1181. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1182. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1183. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1184. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1185. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1186. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1187. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1188. # Calculators Tool
  1189. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1190. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1191. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1192. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1193. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1194. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1195. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1196. # Transformations Tool
  1197. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1198. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1199. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1200. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1201. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1202. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1203. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1204. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1205. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1206. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1207. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1208. # SolderPaste Dispensing Tool
  1209. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1210. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1211. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1212. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1213. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1214. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1215. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1216. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1217. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1218. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1219. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1220. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1221. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1222. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1223. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1224. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1225. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1226. # ###################################################################################
  1227. # ################################ TOOLS 2 ##########################################
  1228. # ###################################################################################
  1229. # Optimal Tool
  1230. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1231. # Check Rules Tool
  1232. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1233. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1234. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1235. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1236. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1237. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1238. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1239. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1240. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1241. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1242. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1243. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1244. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1245. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1246. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1247. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1248. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1249. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1250. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1251. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1252. # QRCode Tool
  1253. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1254. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1255. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1256. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1257. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1258. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1259. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1260. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1261. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1262. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1263. # Copper Thieving Tool
  1264. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1265. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1266. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1267. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1268. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1269. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1270. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1271. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1272. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1273. "tools_copper_thieving_squares_spacing":
  1274. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1275. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1276. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1277. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1278. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1279. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1280. # Fiducials Tool
  1281. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1282. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1283. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1284. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1285. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1286. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1287. # Calibration Tool
  1288. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1289. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1290. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1291. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1292. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1293. # Utilities
  1294. # File associations
  1295. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1296. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1297. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1298. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1299. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1300. }
  1301. # update the Preferences GUI elements with the values in the self.defaults
  1302. self.defaults_write_form()
  1303. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1304. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1305. # #############################################################################
  1306. # ############################## Data #########################################
  1307. # #############################################################################
  1308. self.recent = []
  1309. self.recent_projects = []
  1310. self.clipboard = QtWidgets.QApplication.clipboard()
  1311. self.project_filename = None
  1312. self.toggle_units_ignore = False
  1313. # #############################################################################
  1314. # ########################## LOAD POSTPROCESSORS ##############################
  1315. # #############################################################################
  1316. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1317. # the preprocessor file
  1318. self.preprocessors = load_preprocessors(self)
  1319. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1320. if 'default' in self.preprocessors.keys():
  1321. new_ppp_dict = dict()
  1322. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1323. default_pp = self.preprocessors.pop('default')
  1324. new_ppp_dict['default'] = default_pp
  1325. # then add the rest of the keys
  1326. for name, val_class in self.preprocessors.items():
  1327. new_ppp_dict[name] = val_class
  1328. # and now put back the ordered dict with 'default' key first
  1329. self.preprocessors = new_ppp_dict
  1330. for name in list(self.preprocessors.keys()):
  1331. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1332. if name.partition('_')[0] == 'Paste':
  1333. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1334. continue
  1335. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1336. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1337. if name == 'hpgl':
  1338. continue
  1339. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1340. # #############################################################################
  1341. # ########################## LOAD LANGUAGES ##################################
  1342. # #############################################################################
  1343. self.languages = fcTranslate.load_languages()
  1344. for name in sorted(self.languages.values()):
  1345. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1346. # #############################################################################
  1347. # ############################ APPLY APP LANGUAGE #############################
  1348. # #############################################################################
  1349. ret_val = fcTranslate.apply_language('strings')
  1350. if ret_val == "no language":
  1351. self.inform.emit('[ERROR] %s' %
  1352. _("Could not find the Language files. The App strings are missing."))
  1353. log.debug("Could not find the Language files. The App strings are missing.")
  1354. else:
  1355. # make the current language the current selection on the language combobox
  1356. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1357. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1358. # #############################################################################
  1359. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1360. # #############################################################################
  1361. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1362. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1363. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1364. self.save_defaults(silent=True, first_time=True)
  1365. self.propagate_defaults(silent=True)
  1366. # def auto_save_defaults():
  1367. # try:
  1368. # self.save_defaults(silent=True)
  1369. # self.propagate_defaults(silent=True)
  1370. # finally:
  1371. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1372. # the following lines activates automatic defaults save
  1373. # if user_defaults:
  1374. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1375. # #############################################################################
  1376. # ########################### UPDATE THE OPTIONS ##############################
  1377. # #############################################################################
  1378. self.options = LoudDict()
  1379. # ----------------------------------------------------------------------------------------------------
  1380. # Update the self.options from the self.defaults
  1381. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1382. # -----------------------------------------------------------------------------------------------------
  1383. # Copy app defaults to project options
  1384. for def_key, def_val in self.defaults.items():
  1385. self.options[def_key] = deepcopy(def_val)
  1386. # self.options.update(self.defaults)
  1387. self.gen_form = None
  1388. self.ger_form = None
  1389. self.exc_form = None
  1390. self.geo_form = None
  1391. self.cnc_form = None
  1392. self.tools_form = None
  1393. self.tools2_form = None
  1394. self.fa_form = None
  1395. # Will show the Preferences GUI
  1396. self.show_preferences_gui()
  1397. # Initialize the color box's color in Preferences -> Global -> Color
  1398. self.init_color_pickers_in_preferences_gui()
  1399. # ### End of Data ####
  1400. # #############################################################################
  1401. # ######################## SETUP OBJECT COLLECTION ############################
  1402. # #############################################################################
  1403. self.collection = ObjectCollection(self)
  1404. self.ui.project_tab_layout.addWidget(self.collection.view)
  1405. # ### Adjust tabs width ## ##
  1406. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1407. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1408. self.collection.view.setMinimumWidth(290)
  1409. self.log.debug("Finished creating Object Collection.")
  1410. # #############################################################################
  1411. # ############################## SETUP Plot Area ##############################
  1412. # #############################################################################
  1413. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1414. if self.defaults["global_graphic_engine"] == '3D':
  1415. self.is_legacy = False
  1416. else:
  1417. self.is_legacy = True
  1418. # Event signals disconnect id holders
  1419. self.mp = None
  1420. self.mm = None
  1421. self.mr = None
  1422. self.mdc = None
  1423. self.mp_zc = None
  1424. # Matplotlib axis
  1425. self.axes = None
  1426. if show_splash:
  1427. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1428. "Canvas initialization started."),
  1429. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1430. color=QtGui.QColor("gray"))
  1431. start_plot_time = time.time() # debug
  1432. self.plotcanvas = None
  1433. self.app_cursor = None
  1434. self.hover_shapes = None
  1435. # setup the PlotCanvas
  1436. self.on_plotcanvas_setup()
  1437. end_plot_time = time.time()
  1438. self.used_time = end_plot_time - start_plot_time
  1439. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1440. if show_splash:
  1441. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1442. "Canvas initialization started.\n"
  1443. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1444. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1445. color=QtGui.QColor("gray"))
  1446. self.ui.splitter.setStretchFactor(1, 2)
  1447. # #############################################################################
  1448. # ################################### SYS TRAY ################################
  1449. # #############################################################################
  1450. if self.defaults["global_systray_icon"]:
  1451. self.parent_w = QtWidgets.QWidget()
  1452. if self.cmd_line_headless == 1:
  1453. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1454. headless=True,
  1455. parent=self.parent_w)
  1456. else:
  1457. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1458. parent=self.parent_w)
  1459. # #############################################################################
  1460. # ################################## Worker SETUP #############################
  1461. # #############################################################################
  1462. if self.defaults["global_worker_number"]:
  1463. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1464. else:
  1465. self.workers = WorkerStack(workers_number=2)
  1466. self.worker_task.connect(self.workers.add_task)
  1467. self.log.debug("Finished creating Workers crew.")
  1468. # #############################################################################
  1469. # ################################# Activity Monitor ##########################
  1470. # #############################################################################
  1471. self.activity_view = FlatCAMActivityView(app=self)
  1472. self.ui.infobar.addWidget(self.activity_view)
  1473. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1474. # #############################################################################
  1475. # ################################## Signal handling ##########################
  1476. # #############################################################################
  1477. # ################################# Custom signals ###########################
  1478. # signal for displaying messages in status bar
  1479. self.inform.connect(self.info)
  1480. # signal to be called when the app is quiting
  1481. self.app_quit.connect(self.quit_application)
  1482. self.message.connect(self.message_dialog)
  1483. self.progress.connect(self.set_progress_bar)
  1484. # signals that are emitted when object state changes
  1485. self.object_created.connect(self.on_object_created)
  1486. self.object_changed.connect(self.on_object_changed)
  1487. self.object_plotted.connect(self.on_object_plotted)
  1488. self.plots_updated.connect(self.on_plots_updated)
  1489. # signals emitted when file state change
  1490. self.file_opened.connect(self.register_recent)
  1491. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1492. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1493. # ############# Standard signals ###################
  1494. # ### Menu
  1495. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1496. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1497. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1498. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1499. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1500. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1501. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1502. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1503. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1504. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1505. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1506. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1507. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1508. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1509. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1510. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1511. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1512. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1513. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1514. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1515. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1516. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1517. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1518. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1519. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1520. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1521. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1522. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1523. self.ui.menufile_exit.triggered.connect(self.final_save)
  1524. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1525. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1526. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1527. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1528. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1529. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1530. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1531. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1532. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1533. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1534. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1535. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1536. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1537. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1538. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1539. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1540. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1541. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1542. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1543. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1544. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1545. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1546. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1547. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1548. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1549. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1550. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1551. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1552. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1553. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1554. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1555. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1556. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1557. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1558. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1559. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1560. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1561. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1562. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1563. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1564. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1565. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1566. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1567. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1568. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1569. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1570. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1571. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1572. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1573. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1574. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1575. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1576. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1577. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1578. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1579. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1580. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1581. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1582. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1583. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1584. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1585. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1586. # ToolBar signals
  1587. self.connect_toolbar_signals()
  1588. # Notebook and Plot Tab Area signals
  1589. # make the right click on the notebook tab and plot tab area tab raise a menu
  1590. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1591. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1592. self.on_tab_setup_context_menu()
  1593. # activate initial state
  1594. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1595. # Context Menu
  1596. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1597. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1598. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1599. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1600. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1601. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1602. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1603. self.ui.clearplot.triggered.connect(self.clear_plots)
  1604. self.ui.replot.triggered.connect(self.plot_all)
  1605. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1606. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1607. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1608. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1609. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1610. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1611. # Preferences Plot Area TAB
  1612. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1613. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1614. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1615. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1616. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1617. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1618. # #############################################################################
  1619. # ######################### GUI PREFERENCES SIGNALS ###########################
  1620. # #############################################################################
  1621. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1622. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1623. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1624. )
  1625. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1626. lambda: self.on_toggle_units(no_pref=False))
  1627. # #############################################################################
  1628. # ############################# GUI COLORS SIGNALS ############################
  1629. # #############################################################################
  1630. # Setting plot colors signals
  1631. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1632. self.on_pf_color_entry)
  1633. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1634. self.on_pf_color_button)
  1635. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1636. self.on_pf_color_spinner)
  1637. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1638. self.on_pf_color_slider)
  1639. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1640. self.on_pl_color_entry)
  1641. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1642. self.on_pl_color_button)
  1643. # Setting selection (left - right) colors signals
  1644. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1645. self.on_sf_color_entry)
  1646. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1647. self.on_sf_color_button)
  1648. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1649. self.on_sf_color_spinner)
  1650. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1651. self.on_sf_color_slider)
  1652. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1653. self.on_sl_color_entry)
  1654. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1655. self.on_sl_color_button)
  1656. # Setting selection (right - left) colors signals
  1657. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1658. self.on_alt_sf_color_entry)
  1659. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1660. self.on_alt_sf_color_button)
  1661. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1662. self.on_alt_sf_color_spinner)
  1663. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1664. self.on_alt_sf_color_slider)
  1665. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1666. self.on_alt_sl_color_entry)
  1667. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1668. self.on_alt_sl_color_button)
  1669. # Setting Editor Draw colors signals
  1670. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1671. self.on_draw_color_entry)
  1672. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1673. self.on_draw_color_button)
  1674. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1675. self.on_sel_draw_color_entry)
  1676. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1677. self.on_sel_draw_color_button)
  1678. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1679. self.on_proj_color_entry)
  1680. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1681. self.on_proj_color_button)
  1682. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1683. self.on_proj_color_dis_entry)
  1684. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1685. self.on_proj_color_dis_button)
  1686. # ############################# workspace setting signals #####################
  1687. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1688. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1689. self.on_workspace_modified
  1690. )
  1691. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1692. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1693. # #############################################################################
  1694. # ############################# GUI SETTINGS SIGNALS ##########################
  1695. # #############################################################################
  1696. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1697. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1698. # ########## CNC Job related signals #############
  1699. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1700. self.on_cnc_custom_parameters)
  1701. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1702. self.on_annotation_fontcolor_entry)
  1703. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1704. self.on_annotation_fontcolor_button)
  1705. # ########## Tools related signals #############
  1706. # Film Tool
  1707. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1708. self.on_film_color_entry)
  1709. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1710. self.on_film_color_button)
  1711. # QRCode Tool
  1712. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1713. self.on_qrcode_fill_color_entry)
  1714. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1715. self.on_qrcode_fill_color_button)
  1716. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1717. self.on_qrcode_back_color_entry)
  1718. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1719. self.on_qrcode_back_color_button)
  1720. # portability changed signal
  1721. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1722. # Object list
  1723. self.collection.view.activated.connect(self.on_row_activated)
  1724. self.collection.item_selected.connect(self.on_row_selected)
  1725. self.object_status_changed.connect(self.on_collection_updated)
  1726. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1727. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1728. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1729. # Export Excellon parameters.
  1730. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1731. self.on_update_exc_export
  1732. )
  1733. # call it once to make sure it is updated at startup
  1734. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1735. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1736. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1737. self.on_excellon_defaults_button)
  1738. # when there are arguments at application startup this get launched
  1739. self.args_at_startup[list].connect(self.on_startup_args)
  1740. # #############################################################################
  1741. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1742. # #############################################################################
  1743. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1744. lambda: self.restore_extensions(ext_type='excellon'))
  1745. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1746. lambda: self.restore_extensions(ext_type='gcode'))
  1747. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1748. lambda: self.restore_extensions(ext_type='gerber'))
  1749. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1750. lambda: self.delete_all_extensions(ext_type='excellon'))
  1751. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1752. lambda: self.delete_all_extensions(ext_type='gcode'))
  1753. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1754. lambda: self.delete_all_extensions(ext_type='gerber'))
  1755. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1756. lambda: self.add_extension(ext_type='excellon'))
  1757. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1758. lambda: self.add_extension(ext_type='gcode'))
  1759. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1760. lambda: self.add_extension(ext_type='gerber'))
  1761. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1762. lambda: self.del_extension(ext_type='excellon'))
  1763. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1764. lambda: self.del_extension(ext_type='gcode'))
  1765. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1766. lambda: self.del_extension(ext_type='gerber'))
  1767. # connect the 'Apply' buttons from the Preferences/File Associations
  1768. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1769. lambda: self.on_register_files(obj_type='excellon'))
  1770. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1771. lambda: self.on_register_files(obj_type='gcode'))
  1772. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1773. lambda: self.on_register_files(obj_type='gerber'))
  1774. # #############################################################################
  1775. # ################################ KEYWORDS SIGNALS ###########################
  1776. # #############################################################################
  1777. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1778. lambda: self.restore_extensions(ext_type='keyword'))
  1779. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1780. lambda: self.delete_all_extensions(ext_type='keyword'))
  1781. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1782. lambda: self.add_extension(ext_type='keyword'))
  1783. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1784. lambda: self.del_extension(ext_type='keyword'))
  1785. # splash screen button signal
  1786. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1787. # connect the abort_all_tasks related slots to the related signals
  1788. self.proc_container.idle_flag.connect(self.app_is_idle)
  1789. # signal emitted when a tab is closed in the Plot Area
  1790. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1791. # #####################################################################################
  1792. # ########### FINISHED CONNECTING SIGNALS #############################################
  1793. # #####################################################################################
  1794. self.log.debug("Finished connecting Signals.")
  1795. # #####################################################################################
  1796. # ########################## Other setups #############################################
  1797. # #####################################################################################
  1798. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1799. # depending on from where those tools are called different actions can be done
  1800. self.call_source = 'app'
  1801. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1802. self.tool_tab_locked = False
  1803. # decide if to show or hide the Notebook side of the screen at startup
  1804. if self.defaults["global_project_at_startup"] is True:
  1805. self.ui.splitter.setSizes([1, 1])
  1806. else:
  1807. self.ui.splitter.setSizes([0, 1])
  1808. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1809. self.setup_obj_classes()
  1810. self.setup_component_editor()
  1811. # #####################################################################################
  1812. # ######################### Auto-complete KEYWORDS ####################################
  1813. # #####################################################################################
  1814. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1815. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1816. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1817. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1818. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1819. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1820. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1821. 'mirror', 'ncc',
  1822. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1823. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1824. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1825. 'save', 'save_project',
  1826. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1827. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1828. 'version', 'write_gcode'
  1829. ]
  1830. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1831. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1832. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1833. 'axisoffset',
  1834. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1835. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1836. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1837. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1838. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1839. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1840. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1841. 'spacing_columns',
  1842. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1843. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1844. ]
  1845. self.tcl_keywords = [
  1846. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1847. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1848. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1849. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1850. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1851. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1852. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1853. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1854. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1855. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1856. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1857. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1858. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1859. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1860. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1861. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1862. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1863. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1864. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1865. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1866. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1867. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1868. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1869. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1870. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1871. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1872. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1873. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1874. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1875. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1876. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1877. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1878. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1879. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1880. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1881. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1882. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1883. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1884. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1885. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1886. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1887. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1888. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1889. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1890. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1891. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1892. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1893. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1894. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1895. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1896. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1897. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1898. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1899. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1900. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1901. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1902. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1903. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1904. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1905. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1906. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1907. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1908. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1909. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1910. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1911. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1912. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1913. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1914. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1915. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1916. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1917. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1918. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1919. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1920. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1921. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1922. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1923. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1924. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1925. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1926. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1927. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1928. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1929. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1930. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1931. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1932. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1933. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1934. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1935. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1936. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1937. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1938. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1939. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1940. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1941. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1942. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1943. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1944. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1945. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1946. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1947. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1948. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1949. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1950. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1951. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1952. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1953. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1954. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1955. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1956. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1957. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1958. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1959. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1960. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1961. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1962. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1963. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1964. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1965. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1966. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1967. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1968. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1969. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1970. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1971. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1972. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1973. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1974. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1975. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1976. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1977. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1978. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1979. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1980. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1981. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1982. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1983. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1984. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1985. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1986. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1987. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1988. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1989. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1990. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1991. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1992. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1993. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1994. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1995. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1996. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1997. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1998. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1999. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2000. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2001. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2002. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2003. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2004. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2005. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2006. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2007. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2008. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2009. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2010. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2011. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2012. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2013. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2014. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2015. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2016. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2017. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2018. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2019. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2020. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2021. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2022. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2023. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2024. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2025. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2026. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2027. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2028. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2029. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2030. ]
  2031. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2032. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2033. # ####################################################################################
  2034. # ####################### Shell SETUP ################################################
  2035. # ####################################################################################
  2036. # this will hold the TCL instance
  2037. self.tcl = None
  2038. self.init_tcl()
  2039. self.shell = FCShell(self, version=self.version)
  2040. self.shell._edit.set_model_data(self.myKeywords)
  2041. self.shell.setWindowIcon(self.ui.app_icon)
  2042. self.shell.setWindowTitle("FlatCAM Shell")
  2043. self.shell.resize(*self.defaults["global_shell_shape"])
  2044. self.shell.append_output("FlatCAM %s - " % self.version)
  2045. self.shell.append_output(_("Type >help< to get started\n\n"))
  2046. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2047. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2048. self.ui.shell_dock.setWidget(self.shell)
  2049. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2050. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2051. QtWidgets.QDockWidget.DockWidgetFloatable |
  2052. QtWidgets.QDockWidget.DockWidgetClosable)
  2053. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2054. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2055. if self.defaults["global_shell_at_startup"]:
  2056. self.ui.shell_dock.show()
  2057. else:
  2058. self.ui.shell_dock.hide()
  2059. # ##################################################################################
  2060. # ###################### Tools and Plugins #########################################
  2061. # ##################################################################################
  2062. self.dblsidedtool = None
  2063. self.distance_tool = None
  2064. self.distance_min_tool = None
  2065. self.panelize_tool = None
  2066. self.film_tool = None
  2067. self.paste_tool = None
  2068. self.calculator_tool = None
  2069. self.rules_tool = None
  2070. self.sub_tool = None
  2071. self.move_tool = None
  2072. self.cutout_tool = None
  2073. self.ncclear_tool = None
  2074. self.optimal_tool = None
  2075. self.paint_tool = None
  2076. self.transform_tool = None
  2077. self.properties_tool = None
  2078. self.pdf_tool = None
  2079. self.image_tool = None
  2080. self.pcb_wizard_tool = None
  2081. self.cal_exc_tool = None
  2082. self.qrcode_tool = None
  2083. self.copper_thieving_tool = None
  2084. self.fiducial_tool = None
  2085. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2086. self.install_tools()
  2087. # ##################################################################################
  2088. # ########################### SETUP RECENT ITEMS ###################################
  2089. # ##################################################################################
  2090. self.setup_recent_items()
  2091. # ##################################################################################
  2092. # ########################### BookMarks Manager ####################################
  2093. # ##################################################################################
  2094. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2095. self.install_bookmarks()
  2096. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2097. # ##################################################################################
  2098. # ############################## Tools Database ####################################
  2099. # ##################################################################################
  2100. self.tools_db_tab = None
  2101. # ### System Font Parsing ###
  2102. # self.f_parse = ParseFont(self)
  2103. # self.parse_system_fonts()
  2104. # #####################################################################################
  2105. # ######################## Check for updates ##########################################
  2106. # #####################################################################################
  2107. # Separate thread (Not worker)
  2108. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2109. if (self.beta is False or self.beta is None) and \
  2110. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2111. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2112. self.thr2 = QtCore.QThread()
  2113. self.worker_task.emit({'fcn': self.version_check,
  2114. 'params': []})
  2115. self.thr2.start(QtCore.QThread.LowPriority)
  2116. # #####################################################################################
  2117. # ######################### Register files with FlatCAM; #############################
  2118. # ######################### It works only for Windows for now ########################
  2119. # #####################################################################################
  2120. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2121. self.on_register_files()
  2122. # #####################################################################################
  2123. # ###################### Variables for global usage ###################################
  2124. # #####################################################################################
  2125. # hold the App units
  2126. self.units = 'MM'
  2127. # coordinates for relative position display
  2128. self.rel_point1 = (0, 0)
  2129. self.rel_point2 = (0, 0)
  2130. # variable to store coordinates
  2131. self.pos = (0, 0)
  2132. self.pos_canvas = (0, 0)
  2133. self.pos_jump = (0, 0)
  2134. # variable to store mouse coordinates
  2135. self.mouse = [0, 0]
  2136. # decide if we have a double click or single click
  2137. self.doubleclick = False
  2138. # store here the is_dragging value
  2139. self.event_is_dragging = False
  2140. # variable to store if a command is active (then the var is not None) and which one it is
  2141. self.command_active = None
  2142. # variable to store the status of moving selection action
  2143. # None value means that it's not an selection action
  2144. # True value = a selection from left to right
  2145. # False value = a selection from right to left
  2146. self.selection_type = None
  2147. # List to store the objects that are currently loaded in FlatCAM
  2148. # This list is updated on each object creation or object delete
  2149. self.all_objects_list = list()
  2150. # List to store the objects that are selected
  2151. self.sel_objects_list = list()
  2152. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2153. self.key_modifiers = None
  2154. # Variable to hold the status of the axis
  2155. self.toggle_axis = True
  2156. # Variable to hold the status of the grid lines
  2157. self.toggle_grid_lines = True
  2158. # Variable to store the status of the fullscreen event
  2159. self.toggle_fscreen = False
  2160. # Variable to store the status of the code editor
  2161. self.toggle_codeeditor = False
  2162. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2163. self.click_noproject = False
  2164. self.cursor = None
  2165. # Variable to store the GCODE that was edited
  2166. self.gcode_edited = ""
  2167. self.text_editor_tab = None
  2168. # reference for the self.ui.code_editor
  2169. self.reference_code_editor = None
  2170. self.script_code = ''
  2171. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2172. self.preferences_changed_flag = False
  2173. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2174. self.tools_db_changed_flag = False
  2175. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2176. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2177. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2178. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2179. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2180. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2181. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2182. 'sbp', 'tap', 'xpi']
  2183. self.svg_list = ['svg']
  2184. self.dxf_list = ['dxf']
  2185. self.pdf_list = ['pdf']
  2186. self.prj_list = ['flatprj']
  2187. self.conf_list = ['flatconfig']
  2188. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2189. # flag for polygons not cleared
  2190. self.poly_not_cleared = False
  2191. # VisPy visuals
  2192. self.isHovering = False
  2193. self.notHovering = True
  2194. # Window geometry
  2195. self.x_pos = None
  2196. self.y_pos = None
  2197. self.width = None
  2198. self.height = None
  2199. # when True, the app has to return from any thread
  2200. self.abort_flag = False
  2201. # set the value used in the Windows Title
  2202. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2203. # this holds a widget that is installed in the Plot Area when View Source option is used
  2204. self.source_editor_tab = None
  2205. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2206. # VisPy visuals
  2207. if self.is_legacy is False:
  2208. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2209. else:
  2210. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2211. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2212. # ###############################################################################
  2213. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2214. # ############# It's done only once after install ###############
  2215. # ###############################################################################
  2216. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2217. fac_def_from_file = factory_file.read()
  2218. factory_defaults = json.loads(fac_def_from_file)
  2219. # if the file contain an empty dictionary then save the factory defaults into the file
  2220. if not factory_defaults:
  2221. self.save_factory_defaults(silent_message=False)
  2222. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2223. initial_lay = 'compact'
  2224. self.on_layout(lay=initial_lay)
  2225. # Set the combobox in Preferences to the current layout
  2226. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2227. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2228. factory_file.close()
  2229. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2230. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2231. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2232. # after the first run, this object should be False
  2233. self.defaults["first_run"] = False
  2234. # ###############################################################################
  2235. # ################# ADDING FlatCAM EDITORS section ##############################
  2236. # ###############################################################################
  2237. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2238. # at the first launch of the App , the editors will not be functional.
  2239. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2240. self.exc_editor = FlatCAMExcEditor(self)
  2241. self.grb_editor = FlatCAMGrbEditor(self)
  2242. self.log.debug("Finished adding FlatCAM Editor's.")
  2243. self.set_ui_title(name=_("New Project - Not saved"))
  2244. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2245. current_platform = platform.architecture()[0]
  2246. if current_platform != '64bit':
  2247. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2248. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2249. # ###############################################################################
  2250. # ####################### Finished the CONSTRUCTOR ##############################
  2251. # ###############################################################################
  2252. App.log.debug("END of constructor. Releasing control.")
  2253. # #####################################################################################
  2254. # ########################## SHOW GUI #################################################
  2255. # #####################################################################################
  2256. # if the app is not started as headless, show it
  2257. if self.cmd_line_headless != 1:
  2258. if show_splash:
  2259. # finish the splash
  2260. self.splash.finish(self.ui)
  2261. mgui_settings = QSettings("Open Source", "FlatCAM")
  2262. if mgui_settings.contains("maximized_gui"):
  2263. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2264. if maximized_ui is True:
  2265. self.ui.showMaximized()
  2266. else:
  2267. self.ui.show()
  2268. else:
  2269. self.ui.show()
  2270. if self.defaults["global_systray_icon"]:
  2271. self.trayIcon.show()
  2272. else:
  2273. log.warning("******************* RUNNING HEADLESS *******************")
  2274. # #####################################################################################
  2275. # ########################## START-UP ARGUMENTS #######################################
  2276. # #####################################################################################
  2277. # test if the program was started with a script as parameter
  2278. if self.cmd_line_shellvar:
  2279. try:
  2280. cnt = 0
  2281. command_tcl = 0
  2282. for i in self.cmd_line_shellvar.split(','):
  2283. if i is not None:
  2284. # noinspection PyBroadException
  2285. try:
  2286. command_tcl = eval(i)
  2287. except Exception:
  2288. command_tcl = i
  2289. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2290. cnt += 1
  2291. # if there are Windows paths then replace the path separator with a Unix like one
  2292. if sys.platform == 'win32':
  2293. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2294. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2295. except Exception as ext:
  2296. print("ERROR: ", ext)
  2297. sys.exit(2)
  2298. if self.cmd_line_shellfile:
  2299. try:
  2300. if self.ui.shell_dock.isHidden():
  2301. self.ui.shell_dock.show()
  2302. with open(self.cmd_line_shellfile, "r") as myfile:
  2303. if show_splash:
  2304. self.splash.showMessage('%s: %ssec\n%s' % (
  2305. _("Canvas initialization started.\n"
  2306. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2307. _("Executing Tcl Script ...")),
  2308. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2309. color=QtGui.QColor("gray"))
  2310. cmd_line_shellfile_text = myfile.read()
  2311. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2312. except Exception as ext:
  2313. print("ERROR: ", ext)
  2314. sys.exit(2)
  2315. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2316. # the path/file_name must be enclosed in quotes if it contain spaces
  2317. if App.args:
  2318. self.args_at_startup.emit(App.args)
  2319. if self.old_defaults_found is True:
  2320. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2321. "Please reboot the application to update."))
  2322. self.old_defaults_found = False
  2323. @staticmethod
  2324. def copy_and_overwrite(from_path, to_path):
  2325. """
  2326. From here:
  2327. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2328. :param from_path: source path
  2329. :param to_path: destination path
  2330. :return: None
  2331. """
  2332. if os.path.exists(to_path):
  2333. shutil.rmtree(to_path)
  2334. try:
  2335. shutil.copytree(from_path, to_path)
  2336. except FileNotFoundError:
  2337. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2338. shutil.copytree(from_new_path, to_path)
  2339. def on_startup_args(self, args, silent=False):
  2340. """
  2341. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2342. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2343. :param args: a list containing the application args at startup
  2344. :return: None
  2345. """
  2346. if args is not None:
  2347. args_to_process = args
  2348. else:
  2349. args_to_process = App.args
  2350. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2351. for argument in args_to_process:
  2352. if '.FlatPrj'.lower() in argument.lower():
  2353. try:
  2354. project_name = str(argument)
  2355. if project_name == "":
  2356. if silent is False:
  2357. self.inform.emit(_("Open cancelled."))
  2358. else:
  2359. # self.open_project(project_name)
  2360. run_from_arg = True
  2361. # self.worker_task.emit({'fcn': self.open_project,
  2362. # 'params': [project_name, run_from_arg]})
  2363. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2364. except Exception as e:
  2365. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2366. elif '.FlatConfig'.lower() in argument.lower():
  2367. try:
  2368. file_name = str(argument)
  2369. if file_name == "":
  2370. if silent is False:
  2371. self.inform.emit(_("Open Config file failed."))
  2372. else:
  2373. run_from_arg = True
  2374. # self.worker_task.emit({'fcn': self.open_config_file,
  2375. # 'params': [file_name, run_from_arg]})
  2376. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2377. except Exception as e:
  2378. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2379. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2380. try:
  2381. file_name = str(argument)
  2382. if file_name == "":
  2383. if silent is False:
  2384. self.inform.emit(_("Open Script file failed."))
  2385. else:
  2386. if silent is False:
  2387. self.on_fileopenscript(name=file_name)
  2388. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2389. self.on_filerunscript(name=file_name)
  2390. except Exception as e:
  2391. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2392. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2393. log.debug("App.on_startup_args() --> Quit event.")
  2394. sys.exit()
  2395. elif 'save'.lower() in argument.lower():
  2396. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2397. self.save_defaults()
  2398. else:
  2399. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2400. proc_arg = argument.lower()
  2401. for ext in exc_list:
  2402. proc_ext = ext.replace(' ', '')
  2403. proc_ext = '.%s' % proc_ext
  2404. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2405. file_name = str(argument)
  2406. if file_name == "":
  2407. if silent is False:
  2408. self.inform.emit(_("Open Excellon file failed."))
  2409. else:
  2410. self.on_fileopenexcellon(name=file_name)
  2411. return
  2412. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2413. for ext in gco_list:
  2414. proc_ext = ext.replace(' ', '')
  2415. proc_ext = '.%s' % proc_ext
  2416. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2417. file_name = str(argument)
  2418. if file_name == "":
  2419. if silent is False:
  2420. self.inform.emit(_("Open GCode file failed."))
  2421. else:
  2422. self.on_fileopengcode(name=file_name)
  2423. return
  2424. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2425. for ext in grb_list:
  2426. proc_ext = ext.replace(' ', '')
  2427. proc_ext = '.%s' % proc_ext
  2428. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2429. file_name = str(argument)
  2430. if file_name == "":
  2431. if silent is False:
  2432. self.inform.emit(_("Open Gerber file failed."))
  2433. else:
  2434. self.on_fileopengerber(name=file_name)
  2435. return
  2436. # if it reached here without already returning then the app was registered with a file that it does not
  2437. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2438. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2439. # for arg in args_to_process:
  2440. # if 'FlatCAM.exe' in arg:
  2441. # continue
  2442. # else:
  2443. # sys.exit(2)
  2444. def set_ui_title(self, name):
  2445. """
  2446. Sets the title of the main window.
  2447. :param name: String that store the project path and project name
  2448. :return: None
  2449. """
  2450. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2451. (self.version,
  2452. ('BETA' if self.beta else ''),
  2453. platform.architecture()[0],
  2454. self.engine,
  2455. name)
  2456. )
  2457. def on_theme_change(self, val):
  2458. t_settings = QSettings("Open Source", "FlatCAM")
  2459. t_settings.setValue('theme', val)
  2460. # This will write the setting to the platform specific storage.
  2461. del t_settings
  2462. self.on_app_restart()
  2463. def on_app_restart(self):
  2464. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2465. # be left in the SySTray
  2466. try:
  2467. self.trayIcon.hide()
  2468. except Exception:
  2469. pass
  2470. fcTranslate.restart_program(app=self)
  2471. def defaults_read_form(self):
  2472. """
  2473. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2474. :return: None
  2475. """
  2476. for option in self.defaults_form_fields:
  2477. try:
  2478. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2479. except Exception as e:
  2480. log.debug("App.defaults_read_form() --> %s" % str(e))
  2481. def defaults_write_form(self, factor=None, fl_units=None):
  2482. """
  2483. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2484. self.defaults dictionary.
  2485. :param factor: will apply a factor to the values that written in the GUI elements
  2486. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2487. :return: None
  2488. """
  2489. for option in self.defaults:
  2490. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2491. # try:
  2492. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2493. # except KeyError:
  2494. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2495. # # TODO: Rethink this?
  2496. # pass
  2497. def defaults_write_form_field(self, field, factor=None, units=None):
  2498. """
  2499. Basically it is the worker in the self.defaults_write_form()
  2500. :param field: the GUI element in Preferences GUI to be updated
  2501. :param factor: factor to be applied to the field parameter
  2502. :param units: current FLatCAM measuring units
  2503. :return: None, it updates GUI elements
  2504. """
  2505. try:
  2506. if factor is None:
  2507. if units is None:
  2508. self.defaults_form_fields[field].set_value(self.defaults[field])
  2509. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2510. self.defaults_form_fields[field].set_value(self.defaults[field])
  2511. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2512. self.defaults_form_fields[field].set_value(self.defaults[field])
  2513. else:
  2514. if units is None:
  2515. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2516. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2517. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2518. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2519. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2520. except KeyError:
  2521. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2522. # TODO: Rethink this?
  2523. pass
  2524. except AttributeError:
  2525. log.debug(field)
  2526. def clear_pool(self):
  2527. """
  2528. Clear the multiprocessing pool and calls garbage collector.
  2529. :return: None
  2530. """
  2531. self.pool.close()
  2532. self.pool = Pool()
  2533. self.pool_recreated.emit(self.pool)
  2534. gc.collect()
  2535. def install_tools(self):
  2536. """
  2537. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2538. Instantiation of the Tools classes.
  2539. The order that the tools are installed is important as they can depend on each other install position.
  2540. :return: None
  2541. """
  2542. self.dblsidedtool = DblSidedTool(self)
  2543. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2544. self.cal_exc_tool = ToolCalibration(self)
  2545. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2546. before=self.dblsidedtool.menuAction,
  2547. separator=False)
  2548. self.distance_tool = Distance(self)
  2549. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2550. before=self.ui.menueditorigin,
  2551. separator=False)
  2552. self.distance_min_tool = DistanceMin(self)
  2553. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2554. before=self.ui.menueditorigin,
  2555. separator=True)
  2556. self.panelize_tool = Panelize(self)
  2557. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2558. self.film_tool = Film(self)
  2559. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2560. self.paste_tool = SolderPaste(self)
  2561. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2562. self.calculator_tool = ToolCalculator(self)
  2563. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2564. self.sub_tool = ToolSub(self)
  2565. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2566. self.rules_tool = RulesCheck(self)
  2567. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2568. self.optimal_tool = ToolOptimal(self)
  2569. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2570. self.move_tool = ToolMove(self)
  2571. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2572. before=self.ui.menueditorigin, separator=True)
  2573. self.cutout_tool = CutOut(self)
  2574. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2575. before=self.sub_tool.menuAction)
  2576. self.ncclear_tool = NonCopperClear(self)
  2577. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2578. before=self.sub_tool.menuAction, separator=True)
  2579. self.paint_tool = ToolPaint(self)
  2580. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2581. before=self.sub_tool.menuAction, separator=True)
  2582. self.copper_thieving_tool = ToolCopperThieving(self)
  2583. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2584. self.fiducial_tool = ToolFiducials(self)
  2585. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2586. self.qrcode_tool = QRCode(self)
  2587. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2588. self.transform_tool = ToolTransform(self)
  2589. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2590. self.properties_tool = Properties(self)
  2591. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2592. self.pdf_tool = ToolPDF(self)
  2593. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2594. separator=True)
  2595. self.image_tool = ToolImage(self)
  2596. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2597. separator=True)
  2598. self.pcb_wizard_tool = PcbWizard(self)
  2599. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2600. self.log.debug("Tools are installed.")
  2601. def remove_tools(self):
  2602. """
  2603. Will remove all the actions in the Tool menu.
  2604. :return: None
  2605. """
  2606. for act in self.ui.menutool.actions():
  2607. self.ui.menutool.removeAction(act)
  2608. def init_tools(self):
  2609. """
  2610. Initialize the Tool tab in the notebook side of the central widget.
  2611. Remove the actions in the Tools menu.
  2612. Instantiate again the FlatCAM tools (plugins).
  2613. All this is required when changing the layout: standard, compact etc.
  2614. :return: None
  2615. """
  2616. log.debug("init_tools()")
  2617. # delete the data currently in the Tools Tab and the Tab itself
  2618. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2619. if widget is not None:
  2620. widget.deleteLater()
  2621. self.ui.notebook.removeTab(2)
  2622. # rebuild the Tools Tab
  2623. self.ui.tool_tab = QtWidgets.QWidget()
  2624. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2625. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2626. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2627. self.ui.tool_scroll_area = VerticalScrollArea()
  2628. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2629. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2630. # first remove all of them
  2631. self.remove_tools()
  2632. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2633. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2634. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2635. # third install all of them
  2636. self.install_tools()
  2637. self.log.debug("Tools are initialized.")
  2638. # def parse_system_fonts(self):
  2639. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2640. # 'params': []})
  2641. def connect_toolbar_signals(self):
  2642. """
  2643. Reconnect the signals to the actions in the toolbar.
  2644. This has to be done each time after the FlatCAM tools are removed/installed.
  2645. :return: None
  2646. """
  2647. # Toolbar
  2648. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2649. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2650. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2651. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2652. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2653. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2654. self.ui.replot_btn.triggered.connect(self.plot_all)
  2655. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2656. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2657. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2658. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2659. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2660. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2661. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2662. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2663. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2664. self.ui.delete_btn.triggered.connect(self.on_delete)
  2665. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2666. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2667. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2668. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2669. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2670. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2671. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2672. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2673. # Tools Toolbar Signals
  2674. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2675. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2676. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2677. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2678. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2679. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2680. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2681. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2682. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2683. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2684. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2685. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2686. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2687. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2688. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2689. def object2editor(self):
  2690. """
  2691. Send the current Geometry or Excellon object (if any) into the it's editor.
  2692. :return: None
  2693. """
  2694. self.report_usage("object2editor()")
  2695. # disable the objects menu as it may interfere with the Editors
  2696. self.ui.menuobjects.setDisabled(True)
  2697. edited_object = self.collection.get_active()
  2698. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2699. isinstance(edited_object, FlatCAMExcellon):
  2700. pass
  2701. else:
  2702. self.inform.emit('[WARNING_NOTCL] %s' %
  2703. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2704. return
  2705. if isinstance(edited_object, FlatCAMGeometry):
  2706. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2707. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2708. # we set the notebook to hidden
  2709. self.ui.splitter.setSizes([0, 1])
  2710. if edited_object.multigeo is True:
  2711. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2712. if len(sel_rows) > 1:
  2713. self.inform.emit('[WARNING_NOTCL] %s' %
  2714. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2715. "is not possible.\n"
  2716. "Edit only one geometry at a time."))
  2717. # determine the tool dia of the selected tool
  2718. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2719. # now find the key in the edited_object.tools that has this tooldia
  2720. multi_tool = 1
  2721. for tool in edited_object.tools:
  2722. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2723. multi_tool = tool
  2724. break
  2725. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2726. else:
  2727. self.geo_editor.edit_fcgeometry(edited_object)
  2728. # set call source to the Editor we go into
  2729. self.call_source = 'geo_editor'
  2730. elif isinstance(edited_object, FlatCAMExcellon):
  2731. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2732. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2733. if self.ui.splitter.sizes()[0] == 0:
  2734. self.ui.splitter.setSizes([1, 1])
  2735. self.exc_editor.edit_fcexcellon(edited_object)
  2736. # set call source to the Editor we go into
  2737. self.call_source = 'exc_editor'
  2738. elif isinstance(edited_object, FlatCAMGerber):
  2739. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2740. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2741. if self.ui.splitter.sizes()[0] == 0:
  2742. self.ui.splitter.setSizes([1, 1])
  2743. self.grb_editor.edit_fcgerber(edited_object)
  2744. # set call source to the Editor we go into
  2745. self.call_source = 'grb_editor'
  2746. # make sure that we can't select another object while in Editor Mode:
  2747. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2748. self.ui.project_frame.setDisabled(True)
  2749. # delete any selection shape that might be active as they are not relevant in Editor
  2750. self.delete_selection_shape()
  2751. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2752. self.ui.plot_tab_area.protectTab(0)
  2753. self.inform.emit('[WARNING_NOTCL] %s' %
  2754. _("Editor is activated ..."))
  2755. self.should_we_save = True
  2756. def editor2object(self, cleanup=None):
  2757. """
  2758. Transfers the Geometry or Excellon from it's editor to the current object.
  2759. :return: None
  2760. """
  2761. self.report_usage("editor2object()")
  2762. # re-enable the objects menu that was disabled on entry in Editor mode
  2763. self.ui.menuobjects.setDisabled(False)
  2764. # do not update a geometry or excellon object unless it comes out of an editor
  2765. if self.call_source != 'app':
  2766. edited_obj = self.collection.get_active()
  2767. if cleanup is None:
  2768. msgbox = QtWidgets.QMessageBox()
  2769. msgbox.setText(_("Do you want to save the edited object?"))
  2770. msgbox.setWindowTitle(_("Close Editor"))
  2771. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2772. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2773. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2774. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2775. msgbox.setDefaultButton(bt_yes)
  2776. msgbox.exec_()
  2777. response = msgbox.clickedButton()
  2778. if response == bt_yes:
  2779. # clean the Tools Tab
  2780. self.ui.tool_scroll_area.takeWidget()
  2781. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2782. self.ui.notebook.setTabText(2, "Tool")
  2783. if isinstance(edited_obj, FlatCAMGeometry):
  2784. obj_type = "Geometry"
  2785. if cleanup is None:
  2786. self.geo_editor.update_fcgeometry(edited_obj)
  2787. self.geo_editor.update_options(edited_obj)
  2788. self.geo_editor.deactivate()
  2789. # update the geo object options so it is including the bounding box values
  2790. try:
  2791. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2792. edited_obj.options['xmin'] = xmin
  2793. edited_obj.options['ymin'] = ymin
  2794. edited_obj.options['xmax'] = xmax
  2795. edited_obj.options['ymax'] = ymax
  2796. except AttributeError as e:
  2797. self.inform.emit('[WARNING] %s' %
  2798. _("Object empty after edit."))
  2799. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2800. elif isinstance(edited_obj, FlatCAMGerber):
  2801. obj_type = "Gerber"
  2802. if cleanup is None:
  2803. self.grb_editor.update_fcgerber()
  2804. self.grb_editor.update_options(edited_obj)
  2805. self.grb_editor.deactivate_grb_editor()
  2806. # delete the old object (the source object) if it was an empty one
  2807. try:
  2808. if len(edited_obj.solid_geometry) == 0:
  2809. old_name = edited_obj.options['name']
  2810. self.collection.set_active(old_name)
  2811. self.collection.delete_active()
  2812. except TypeError:
  2813. # if the solid_geometry is a single Polygon the len() will not work
  2814. # in any case, falling here means that we have something in the solid_geometry, even if only
  2815. # a single Polygon, therefore we pass this
  2816. pass
  2817. # restore GUI to the Selected TAB
  2818. # Remove anything else in the GUI
  2819. self.ui.selected_scroll_area.takeWidget()
  2820. # Switch notebook to Selected page
  2821. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2822. elif isinstance(edited_obj, FlatCAMExcellon):
  2823. obj_type = "Excellon"
  2824. if cleanup is None:
  2825. self.exc_editor.update_fcexcellon(edited_obj)
  2826. self.exc_editor.update_options(edited_obj)
  2827. self.exc_editor.deactivate()
  2828. # delete the old object (the source object) if it was an empty one
  2829. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2830. old_name = edited_obj.options['name']
  2831. self.collection.set_active(old_name)
  2832. self.collection.delete_active()
  2833. # restore GUI to the Selected TAB
  2834. # Remove anything else in the GUI
  2835. self.ui.tool_scroll_area.takeWidget()
  2836. # Switch notebook to Selected page
  2837. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2838. else:
  2839. self.inform.emit('[WARNING_NOTCL] %s' %
  2840. _("Select a Gerber, Geometry or Excellon Object to update."))
  2841. return
  2842. self.inform.emit('[selected] %s %s' %
  2843. (obj_type, _("is updated, returning to App...")))
  2844. elif response == bt_no:
  2845. # clean the Tools Tab
  2846. self.ui.tool_scroll_area.takeWidget()
  2847. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2848. self.ui.notebook.setTabText(2, "Tool")
  2849. if isinstance(edited_obj, FlatCAMGeometry):
  2850. self.geo_editor.deactivate()
  2851. elif isinstance(edited_obj, FlatCAMGerber):
  2852. self.grb_editor.deactivate_grb_editor()
  2853. elif isinstance(edited_obj, FlatCAMExcellon):
  2854. self.exc_editor.deactivate()
  2855. # set focus on the project tab
  2856. else:
  2857. self.inform.emit('[WARNING_NOTCL] %s' %
  2858. _("Select a Gerber, Geometry or Excellon Object to update."))
  2859. return
  2860. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2861. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2862. elif response == bt_cancel:
  2863. return
  2864. else:
  2865. if isinstance(edited_obj, FlatCAMGeometry):
  2866. self.geo_editor.deactivate()
  2867. elif isinstance(edited_obj, FlatCAMGerber):
  2868. self.grb_editor.deactivate_grb_editor()
  2869. elif isinstance(edited_obj, FlatCAMExcellon):
  2870. self.exc_editor.deactivate()
  2871. else:
  2872. self.inform.emit('[WARNING_NOTCL] %s' %
  2873. _("Select a Gerber, Geometry or Excellon Object to update."))
  2874. return
  2875. # if notebook is hidden we show it
  2876. if self.ui.splitter.sizes()[0] == 0:
  2877. self.ui.splitter.setSizes([1, 1])
  2878. # restore the call_source to app
  2879. self.call_source = 'app'
  2880. edited_obj.plot()
  2881. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2882. self.ui.plot_tab_area.protectTab(0)
  2883. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2884. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2885. self.ui.project_frame.setDisabled(False)
  2886. def get_last_folder(self):
  2887. """
  2888. Get the folder path from where the last file was opened.
  2889. :return: String, last opened folder path
  2890. """
  2891. return self.defaults["global_last_folder"]
  2892. def get_last_save_folder(self):
  2893. """
  2894. Get the folder path from where the last file was saved.
  2895. :return: String, last saved folder path
  2896. """
  2897. loc = self.defaults["global_last_save_folder"]
  2898. if loc is None:
  2899. loc = self.defaults["global_last_folder"]
  2900. if loc is None:
  2901. loc = os.path.dirname(__file__)
  2902. return loc
  2903. def report_usage(self, resource):
  2904. """
  2905. Increments usage counter for the given resource
  2906. in self.defaults['global_stats'].
  2907. :param resource: Name of the resource.
  2908. :return: None
  2909. """
  2910. if resource in self.defaults['global_stats']:
  2911. self.defaults['global_stats'][resource] += 1
  2912. else:
  2913. self.defaults['global_stats'][resource] = 1
  2914. def init_tcl(self):
  2915. """
  2916. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2917. :return: None
  2918. """
  2919. if hasattr(self, 'tcl') and self.tcl is not None:
  2920. # self.tcl = None
  2921. # TODO we need to clean non default variables and procedures here
  2922. # new object cannot be used here as it will not remember values created for next passes,
  2923. # because tcl was execudted in old instance of TCL
  2924. pass
  2925. else:
  2926. self.tcl = tk.Tcl()
  2927. self.setup_shell()
  2928. self.log.debug("TCL Shell has been initialized.")
  2929. # TODO: This shouldn't be here.
  2930. class TclErrorException(Exception):
  2931. """
  2932. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2933. """
  2934. pass
  2935. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2936. """
  2937. Shows a message on the FlatCAM Shell
  2938. :param msg: Message to display.
  2939. :param show: Opens the shell.
  2940. :param error: Shows the message as an error.
  2941. :param warning: Shows the message as an warning.
  2942. :param success: Shows the message as an success.
  2943. :param selected: Indicate that something was selected on canvas
  2944. :return: None
  2945. """
  2946. if show:
  2947. self.ui.shell_dock.show()
  2948. try:
  2949. if error:
  2950. self.shell.append_error(msg + "\n")
  2951. elif warning:
  2952. self.shell.append_warning(msg + "\n")
  2953. elif success:
  2954. self.shell.append_success(msg + "\n")
  2955. elif selected:
  2956. self.shell.append_selected(msg + "\n")
  2957. else:
  2958. self.shell.append_output(msg + "\n")
  2959. except AttributeError:
  2960. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2961. def raise_tcl_unknown_error(self, unknownException):
  2962. """
  2963. Raise exception if is different type than TclErrorException
  2964. this is here mainly to show unknown errors inside TCL shell console.
  2965. :param unknownException:
  2966. :return:
  2967. """
  2968. if not isinstance(unknownException, self.TclErrorException):
  2969. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2970. else:
  2971. raise unknownException
  2972. def display_tcl_error(self, error, error_info=None):
  2973. """
  2974. Escape bracket [ with '\' otherwise there is error
  2975. "ERROR: missing close-bracket" instead of real error
  2976. :param error: it may be text or exception
  2977. :param error_info: Some informations about the error
  2978. :return: None
  2979. """
  2980. if isinstance(error, Exception):
  2981. exc_type, exc_value, exc_traceback = error_info
  2982. if not isinstance(error, self.TclErrorException):
  2983. show_trace = 1
  2984. else:
  2985. show_trace = int(self.defaults['global_verbose_error_level'])
  2986. if show_trace > 0:
  2987. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2988. trc_formated = []
  2989. for a in reversed(trc):
  2990. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2991. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2992. else:
  2993. text = "%s" % error
  2994. else:
  2995. text = error
  2996. text = text.replace('[', '\\[').replace('"', '\\"')
  2997. self.tcl.eval('return -code error "%s"' % text)
  2998. def raise_tcl_error(self, text):
  2999. """
  3000. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3001. :param text: text of error
  3002. :return: raise exception
  3003. """
  3004. self.display_tcl_error(text)
  3005. raise self.TclErrorException(text)
  3006. def exec_command(self, text, no_echo=False):
  3007. """
  3008. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3009. Also handles execution in separated threads
  3010. :param text: FlatCAM TclCommand with parameters
  3011. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3012. will create crashes of the _Expandable_Edit widget
  3013. :return: output if there was any
  3014. """
  3015. self.report_usage('exec_command')
  3016. result = self.exec_command_test(text, False, no_echo=no_echo)
  3017. # MS: added this method call so the geometry is updated once the TCL command is executed
  3018. # if no_plot is None:
  3019. # self.plot_all()
  3020. return result
  3021. def exec_command_test(self, text, reraise=True, no_echo=False):
  3022. """
  3023. Same as exec_command(...) with additional control over exceptions.
  3024. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3025. :param text: Input command
  3026. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3027. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3028. will create crashes of the _Expandable_Edit widget
  3029. :return: Output from the command
  3030. """
  3031. tcl_command_string = str(text)
  3032. try:
  3033. if no_echo is False:
  3034. self.shell.open_proccessing() # Disables input box.
  3035. result = self.tcl.eval(str(tcl_command_string))
  3036. if result != 'None' and no_echo is False:
  3037. self.shell.append_output(result + '\n')
  3038. except tk.TclError as e:
  3039. # This will display more precise answer if something in TCL shell fails
  3040. result = self.tcl.eval("set errorInfo")
  3041. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3042. if no_echo is False:
  3043. self.shell.append_error('ERROR: ' + result + '\n')
  3044. # Show error in console and just return or in test raise exception
  3045. if reraise:
  3046. raise e
  3047. finally:
  3048. if no_echo is False:
  3049. self.shell.close_proccessing()
  3050. pass
  3051. return result
  3052. # """
  3053. # Code below is unsused. Saved for later.
  3054. # """
  3055. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3056. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3057. # self.log.debug(parts)
  3058. # try:
  3059. # if parts[0] not in commands:
  3060. # self.shell.append_error("Unknown command\n")
  3061. # return
  3062. #
  3063. # #import inspect
  3064. # #inspect.getargspec(someMethod)
  3065. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3066. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3067. # self.shell.append_error(
  3068. # "Command %s takes %d arguments. %d given.\n" %
  3069. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3070. # )
  3071. # return
  3072. #
  3073. # cmdfcn = commands[parts[0]]["fcn"]
  3074. # cmdconv = commands[parts[0]]["converters"]
  3075. # if len(parts) - 1 > 0:
  3076. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3077. # else:
  3078. # retval = cmdfcn()
  3079. # retfcn = commands[parts[0]]["retfcn"]
  3080. # if retval and retfcn(retval):
  3081. # self.shell.append_output(retfcn(retval) + "\n")
  3082. #
  3083. # except Exception as e:
  3084. # #self.shell.append_error(''.join(traceback.format_exc()))
  3085. # #self.shell.append_error("?\n")
  3086. # self.shell.append_error(str(e) + "\n")
  3087. def info(self, msg):
  3088. """
  3089. Informs the user. Normally on the status bar, optionally
  3090. also on the shell.
  3091. :param msg: Text to write.
  3092. :return: None
  3093. """
  3094. # Type of message in brackets at the beginning of the message.
  3095. match = re.search("\[([^\]]+)\](.*)", msg)
  3096. if match:
  3097. level = match.group(1)
  3098. msg_ = match.group(2)
  3099. self.ui.fcinfo.set_status(str(msg_), level=level)
  3100. if level.lower() == "error":
  3101. self.shell_message(msg, error=True, show=True)
  3102. elif level.lower() == "warning":
  3103. self.shell_message(msg, warning=True, show=True)
  3104. elif level.lower() == "error_notcl":
  3105. self.shell_message(msg, error=True, show=False)
  3106. elif level.lower() == "warning_notcl":
  3107. self.shell_message(msg, warning=True, show=False)
  3108. elif level.lower() == "success":
  3109. self.shell_message(msg, success=True, show=False)
  3110. elif level.lower() == "selected":
  3111. self.shell_message(msg, selected=True, show=False)
  3112. else:
  3113. self.shell_message(msg, show=False)
  3114. else:
  3115. self.ui.fcinfo.set_status(str(msg), level="info")
  3116. # make sure that if the message is to clear the infobar with a space
  3117. # is not printed over and over on the shell
  3118. if msg != '':
  3119. self.shell_message(msg)
  3120. def restore_toolbar_view(self):
  3121. """
  3122. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3123. was saved in the defaults dictionary.
  3124. :return: None
  3125. """
  3126. tb = self.defaults["global_toolbar_view"]
  3127. if tb & 1:
  3128. self.ui.toolbarfile.setVisible(True)
  3129. else:
  3130. self.ui.toolbarfile.setVisible(False)
  3131. if tb & 2:
  3132. self.ui.toolbargeo.setVisible(True)
  3133. else:
  3134. self.ui.toolbargeo.setVisible(False)
  3135. if tb & 4:
  3136. self.ui.toolbarview.setVisible(True)
  3137. else:
  3138. self.ui.toolbarview.setVisible(False)
  3139. if tb & 8:
  3140. self.ui.toolbartools.setVisible(True)
  3141. else:
  3142. self.ui.toolbartools.setVisible(False)
  3143. if tb & 16:
  3144. self.ui.exc_edit_toolbar.setVisible(True)
  3145. else:
  3146. self.ui.exc_edit_toolbar.setVisible(False)
  3147. if tb & 32:
  3148. self.ui.geo_edit_toolbar.setVisible(True)
  3149. else:
  3150. self.ui.geo_edit_toolbar.setVisible(False)
  3151. if tb & 64:
  3152. self.ui.grb_edit_toolbar.setVisible(True)
  3153. else:
  3154. self.ui.grb_edit_toolbar.setVisible(False)
  3155. if tb & 128:
  3156. self.ui.snap_toolbar.setVisible(True)
  3157. else:
  3158. self.ui.snap_toolbar.setVisible(False)
  3159. if tb & 256:
  3160. self.ui.toolbarshell.setVisible(True)
  3161. else:
  3162. self.ui.toolbarshell.setVisible(False)
  3163. def load_defaults(self, filename):
  3164. """
  3165. Loads the aplication's default settings from current_defaults.FlatConfig into
  3166. ``self.defaults``.
  3167. :return: None
  3168. """
  3169. try:
  3170. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3171. options = f.read()
  3172. f.close()
  3173. except IOError:
  3174. self.log.error("Could not load defaults file.")
  3175. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3176. # in case the defaults file can't be loaded, show all toolbars
  3177. self.defaults["global_toolbar_view"] = 511
  3178. return
  3179. try:
  3180. defaults = json.loads(options)
  3181. except Exception:
  3182. # in case the defaults file can't be loaded, show all toolbars
  3183. self.defaults["global_toolbar_view"] = 511
  3184. e = sys.exc_info()[0]
  3185. App.log.error(str(e))
  3186. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3187. return
  3188. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3189. for k, v in defaults.items():
  3190. if k in self.defaults:
  3191. self.defaults[k] = v
  3192. # delete old factory defaults
  3193. try:
  3194. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3195. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3196. os.remove(fact_def_file_path)
  3197. # recreate a new factory defaults file and save the factory defaults data into it
  3198. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3199. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3200. f_f_def_s.close()
  3201. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3202. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3203. except Exception as e:
  3204. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3205. self.old_defaults_found = True
  3206. else:
  3207. self.defaults.update(defaults)
  3208. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3209. def on_import_preferences(self):
  3210. """
  3211. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3212. ``self.defaults``.
  3213. :return: None
  3214. """
  3215. self.report_usage("on_import_preferences")
  3216. App.log.debug("on_import_preferences()")
  3217. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3218. try:
  3219. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3220. directory=self.data_path,
  3221. filter=filter_)
  3222. except TypeError:
  3223. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3224. filter=filter_)
  3225. filename = str(filename)
  3226. if filename == "":
  3227. self.inform.emit('[WARNING_NOTCL] %s' %
  3228. _("FlatCAM preferences import cancelled."))
  3229. else:
  3230. try:
  3231. f = open(filename)
  3232. options = f.read()
  3233. f.close()
  3234. except IOError:
  3235. self.log.error("Could not load defaults file.")
  3236. self.inform.emit('[ERROR_NOTCL] %s' %
  3237. _("Could not load defaults file."))
  3238. return
  3239. try:
  3240. defaults_from_file = json.loads(options)
  3241. except Exception:
  3242. e = sys.exc_info()[0]
  3243. App.log.error(str(e))
  3244. self.inform.emit('[ERROR_NOTCL] %s' %
  3245. _("Failed to parse defaults file."))
  3246. return
  3247. self.defaults.update(defaults_from_file)
  3248. self.on_preferences_edited()
  3249. self.inform.emit('[success] %s: %s' %
  3250. (_("Imported Defaults from"), filename))
  3251. def on_export_preferences(self):
  3252. """
  3253. Save the defaults dictionary to a file.
  3254. :return: None
  3255. """
  3256. self.report_usage("on_export_preferences")
  3257. App.log.debug("on_export_preferences()")
  3258. defaults_file_content = None
  3259. self.date = str(datetime.today()).rpartition('.')[0]
  3260. self.date = ''.join(c for c in self.date if c not in ':-')
  3261. self.date = self.date.replace(' ', '_')
  3262. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3263. try:
  3264. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3265. caption=_("Export FlatCAM Preferences"),
  3266. directory=self.data_path + '/preferences_' + self.date,
  3267. filter=filter__
  3268. )
  3269. except TypeError:
  3270. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3271. filter=filter__)
  3272. filename = str(filename)
  3273. defaults_from_file = {}
  3274. if filename == "":
  3275. self.inform.emit('[WARNING_NOTCL] %s' %
  3276. _("FlatCAM preferences export cancelled."))
  3277. return
  3278. else:
  3279. try:
  3280. f = open(filename, 'w')
  3281. defaults_file_content = f.read()
  3282. f.close()
  3283. except PermissionError:
  3284. self.inform.emit('[WARNING] %s' %
  3285. _("Permission denied, saving not possible.\n"
  3286. "Most likely another app is holding the file open and not accessible."))
  3287. return
  3288. except IOError:
  3289. App.log.debug('Creating a new preferences file ...')
  3290. f = open(filename, 'w')
  3291. json.dump({}, f)
  3292. f.close()
  3293. except Exception:
  3294. e = sys.exc_info()[0]
  3295. App.log.error("Could not load defaults file.")
  3296. App.log.error(str(e))
  3297. self.inform.emit('[ERROR_NOTCL] %s' %
  3298. _("Could not load preferences file."))
  3299. return
  3300. try:
  3301. defaults_from_file = json.loads(defaults_file_content)
  3302. except Exception:
  3303. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3304. # Update options
  3305. self.defaults_read_form()
  3306. defaults_from_file.update(self.defaults)
  3307. self.propagate_defaults(silent=True)
  3308. # Save update options
  3309. try:
  3310. f = open(filename, "w")
  3311. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3312. f.close()
  3313. except Exception:
  3314. self.inform.emit('[ERROR_NOTCL] %s' %
  3315. _("Failed to write defaults to file."))
  3316. return
  3317. if self.defaults["global_open_style"] is False:
  3318. self.file_opened.emit("preferences", filename)
  3319. self.file_saved.emit("preferences", filename)
  3320. self.inform.emit('[success] %s: %s' %
  3321. (_("Exported preferences to"), filename))
  3322. def on_preferences_open_folder(self):
  3323. """
  3324. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3325. :return: None
  3326. """
  3327. self.report_usage("on_preferences_open_folder()")
  3328. if sys.platform == 'win32':
  3329. subprocess.Popen('explorer %s' % self.data_path)
  3330. elif sys.platform == 'darwin':
  3331. os.system('open "%s"' % self.data_path)
  3332. else:
  3333. subprocess.Popen(['xdg-open', self.data_path])
  3334. self.inform.emit('[success] %s' %
  3335. _("FlatCAM Preferences Folder opened."))
  3336. def save_geometry(self, x, y, width, height, notebook_width):
  3337. """
  3338. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3339. launch of the application.
  3340. :param x: X position of the main window
  3341. :param y: Y position of the main window
  3342. :param width: width of the main window
  3343. :param height: height of the main window
  3344. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3345. :return: None
  3346. """
  3347. self.defaults["global_def_win_x"] = x
  3348. self.defaults["global_def_win_y"] = y
  3349. self.defaults["global_def_win_w"] = width
  3350. self.defaults["global_def_win_h"] = height
  3351. self.defaults["global_def_notebook_width"] = notebook_width
  3352. self.save_defaults()
  3353. def restore_main_win_geom(self):
  3354. try:
  3355. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3356. self.defaults["global_def_win_y"],
  3357. self.defaults["global_def_win_w"],
  3358. self.defaults["global_def_win_h"])
  3359. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3360. except KeyError as e:
  3361. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3362. def message_dialog(self, title, message, kind="info"):
  3363. """
  3364. Builds and show a custom QMessageBox to be used in FlatCAM.
  3365. :param title: title of the QMessageBox
  3366. :param message: message to be displayed
  3367. :param kind: type of QMessageBox; will display a specific icon.
  3368. :return:
  3369. """
  3370. icon = {"info": QtWidgets.QMessageBox.Information,
  3371. "warning": QtWidgets.QMessageBox.Warning,
  3372. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3373. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3374. dlg.setText(message)
  3375. dlg.exec_()
  3376. def register_recent(self, kind, filename):
  3377. """
  3378. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3379. dictionary.
  3380. :param kind: type of file that was opened
  3381. :param filename: the path and file name for the file that was opened
  3382. :return:
  3383. """
  3384. self.log.debug("register_recent()")
  3385. self.log.debug(" %s" % kind)
  3386. self.log.debug(" %s" % filename)
  3387. record = {'kind': str(kind), 'filename': str(filename)}
  3388. if record in self.recent:
  3389. return
  3390. if record in self.recent_projects:
  3391. return
  3392. if record['kind'] == 'project':
  3393. self.recent_projects.insert(0, record)
  3394. else:
  3395. self.recent.insert(0, record)
  3396. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3397. self.recent.pop()
  3398. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3399. self.recent_projects.pop()
  3400. try:
  3401. f = open(self.data_path + '/recent.json', 'w')
  3402. except IOError:
  3403. App.log.error("Failed to open recent items file for writing.")
  3404. self.inform.emit('[ERROR_NOTCL] %s' %
  3405. _('Failed to open recent files file for writing.'))
  3406. return
  3407. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3408. f.close()
  3409. try:
  3410. fp = open(self.data_path + '/recent_projects.json', 'w')
  3411. except IOError:
  3412. App.log.error("Failed to open recent items file for writing.")
  3413. self.inform.emit('[ERROR_NOTCL] %s' %
  3414. _('Failed to open recent projects file for writing.'))
  3415. return
  3416. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3417. fp.close()
  3418. # Re-build the recent items menu
  3419. self.setup_recent_items()
  3420. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3421. """
  3422. Creates a new specialized FlatCAMObj and attaches it to the application,
  3423. this is, updates the GUI accordingly, any other records and plots it.
  3424. This method is thread-safe.
  3425. Notes:
  3426. * If the name is in use, the self.collection will modify it
  3427. when appending it to the collection. There is no need to handle
  3428. name conflicts here.
  3429. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3430. :type kind: str
  3431. :param name: Name for the object.
  3432. :type name: str
  3433. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3434. The function is called with 2 parameters: the new object and the App instance.
  3435. :type initialize: function
  3436. :param active:
  3437. :param fit:
  3438. :param plot: If to plot the resulting object
  3439. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3440. self.colleaction
  3441. :return: None
  3442. :rtype: None
  3443. """
  3444. App.log.debug("new_object()")
  3445. obj_plot = plot
  3446. obj_autoselected = autoselected
  3447. t0 = time.time() # Debug
  3448. # ## Create object
  3449. classdict = {
  3450. "gerber": FlatCAMGerber,
  3451. "excellon": FlatCAMExcellon,
  3452. "cncjob": FlatCAMCNCjob,
  3453. "geometry": FlatCAMGeometry,
  3454. "script": FlatCAMScript,
  3455. "document": FlatCAMDocument
  3456. }
  3457. App.log.debug("Calling object constructor...")
  3458. # Object creation/instantiation
  3459. obj = classdict[kind](name)
  3460. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3461. # IMPORTANT
  3462. # The key names in defaults and options dictionary's are not random:
  3463. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3464. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3465. # copied to self.options. After that, below, depending on the type of
  3466. # object that is created, it will strip the name of the object and the underline (if the original key was
  3467. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3468. # "toolchange"
  3469. for option in self.options:
  3470. if option.find(kind + "_") == 0:
  3471. oname = option[len(kind) + 1:]
  3472. obj.options[oname] = self.options[option]
  3473. obj.isHovering = False
  3474. obj.notHovering = True
  3475. # Initialize as per user request
  3476. # User must take care to implement initialize
  3477. # in a thread-safe way as is is likely that we
  3478. # have been invoked in a separate thread.
  3479. t1 = time.time()
  3480. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3481. try:
  3482. return_value = initialize(obj, self)
  3483. except Exception as e:
  3484. msg = '[ERROR_NOTCL] %s' % \
  3485. _("An internal error has ocurred. See shell.\n")
  3486. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3487. msg += traceback.format_exc()
  3488. self.inform.emit(msg)
  3489. # if str(e) == "Empty Geometry":
  3490. # self.inform.emit("[ERROR_NOTCL] )
  3491. # else:
  3492. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3493. return "fail"
  3494. t2 = time.time()
  3495. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3496. if return_value == 'fail':
  3497. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3498. return "fail"
  3499. # Check units and convert if necessary
  3500. # This condition CAN be true because initialize() can change obj.units
  3501. if self.options["units"].upper() != obj.units.upper():
  3502. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3503. obj.convert_units(self.options["units"])
  3504. t3 = time.time()
  3505. self.log.debug("%f seconds converting units." % (t3 - t2))
  3506. # Create the bounding box for the object and then add the results to the obj.options
  3507. # But not for Scripts or for Documents
  3508. if kind != 'document' and kind != 'script':
  3509. try:
  3510. xmin, ymin, xmax, ymax = obj.bounds()
  3511. obj.options['xmin'] = xmin
  3512. obj.options['ymin'] = ymin
  3513. obj.options['xmax'] = xmax
  3514. obj.options['ymax'] = ymax
  3515. except Exception as e:
  3516. log.warning("The object has no bounds properties. %s" % str(e))
  3517. return "fail"
  3518. # update the KeyWords list with the name of the file
  3519. self.myKeywords.append(obj.options['name'])
  3520. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3521. # Move the object to the main thread and let the app know that it is available.
  3522. obj.moveToThread(self.main_thread)
  3523. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3524. return obj
  3525. def new_excellon_object(self):
  3526. """
  3527. Creates a new, blank Excellon object.
  3528. :return: None
  3529. """
  3530. self.report_usage("new_excellon_object()")
  3531. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3532. def new_geometry_object(self):
  3533. """
  3534. Creates a new, blank and single-tool Geometry object.
  3535. :return: None
  3536. """
  3537. self.report_usage("new_geometry_object()")
  3538. def initialize(obj, app):
  3539. obj.multitool = False
  3540. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3541. def new_gerber_object(self):
  3542. """
  3543. Creates a new, blank Gerber object.
  3544. :return: None
  3545. """
  3546. self.report_usage("new_gerber_object()")
  3547. def initialize(grb_obj, app):
  3548. grb_obj.multitool = False
  3549. grb_obj.source_file = []
  3550. grb_obj.multigeo = False
  3551. grb_obj.follow = False
  3552. grb_obj.apertures = {}
  3553. grb_obj.solid_geometry = []
  3554. try:
  3555. grb_obj.options['xmin'] = 0
  3556. grb_obj.options['ymin'] = 0
  3557. grb_obj.options['xmax'] = 0
  3558. grb_obj.options['ymax'] = 0
  3559. except KeyError:
  3560. pass
  3561. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3562. def new_script_object(self, name=None, text=None):
  3563. """
  3564. Creates a new, blank TCL Script object.
  3565. :param name: a name for the new object
  3566. :param text: pass a source file to the newly created script to be loaded in it
  3567. :return: None
  3568. """
  3569. self.report_usage("new_script_object()")
  3570. if text is not None:
  3571. new_source_file = text
  3572. else:
  3573. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3574. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3575. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3576. "ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3577. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3578. "ListSys, MillDrills,\n"\
  3579. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3580. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3581. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3582. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3583. "# SubtractRectangle, Version, WriteGCode\n"
  3584. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3585. '# %s:\n' % _('TCL Tutorial is here') + \
  3586. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3587. '# %s:\n' % _("FlatCAM commands list")
  3588. new_source_file += commands_list + '\n'
  3589. def initialize(obj, app):
  3590. obj.source_file = deepcopy(new_source_file)
  3591. if name is None:
  3592. outname = 'new_script'
  3593. else:
  3594. outname = name
  3595. self.new_object('script', outname, initialize, plot=False)
  3596. def new_document_object(self):
  3597. """
  3598. Creates a new, blank Document object.
  3599. :return: None
  3600. """
  3601. self.report_usage("new_document_object()")
  3602. def initialize(obj, app):
  3603. obj.source_file = ""
  3604. self.new_object('document', 'new_document', initialize, plot=False)
  3605. def on_object_created(self, obj, plot, auto_select):
  3606. """
  3607. Event callback for object creation.
  3608. It will add the new object to the collection. After that it will plot the object in a threaded way
  3609. :param obj: The newly created FlatCAM object.
  3610. :param plot: if the newly create object t obe plotted
  3611. :param auto_select: if the newly created object to be autoselected after creation
  3612. :return: None
  3613. """
  3614. t0 = time.time() # DEBUG
  3615. self.log.debug("on_object_created()")
  3616. # The Collection might change the name if there is a collision
  3617. self.collection.append(obj)
  3618. # after adding the object to the collection always update the list of objects that are in the collection
  3619. self.all_objects_list = self.collection.get_list()
  3620. # self.inform.emit('[selected] %s created & selected: %s' %
  3621. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3622. if obj.kind == 'gerber':
  3623. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3624. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3625. elif obj.kind == 'excellon':
  3626. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3627. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3628. elif obj.kind == 'cncjob':
  3629. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3630. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3631. elif obj.kind == 'geometry':
  3632. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3633. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3634. elif obj.kind == 'script':
  3635. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3636. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3637. elif obj.kind == 'document':
  3638. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3639. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3640. # update the SHELL auto-completer model with the name of the new object
  3641. self.shell._edit.set_model_data(self.myKeywords)
  3642. if auto_select:
  3643. # select the just opened object but deselect the previous ones
  3644. self.collection.set_all_inactive()
  3645. self.collection.set_active(obj.options["name"])
  3646. else:
  3647. self.collection.set_all_inactive()
  3648. # here it is done the object plotting
  3649. def worker_task(t_obj):
  3650. with self.proc_container.new(_("Plotting")):
  3651. if isinstance(t_obj, FlatCAMCNCjob):
  3652. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3653. else:
  3654. t_obj.plot()
  3655. t1 = time.time() # DEBUG
  3656. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3657. self.object_plotted.emit(t_obj)
  3658. # Send to worker
  3659. # self.worker.add_task(worker_task, [self])
  3660. if plot is True:
  3661. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3662. def on_object_changed(self, obj):
  3663. """
  3664. Called whenever the geometry of the object was changed in some way.
  3665. This require the update of it's bounding values so it can be the selected on canvas.
  3666. Update the bounding box data from obj.options
  3667. :param obj: the object that was changed
  3668. :return: None
  3669. """
  3670. xmin, ymin, xmax, ymax = obj.bounds()
  3671. obj.options['xmin'] = xmin
  3672. obj.options['ymin'] = ymin
  3673. obj.options['xmax'] = xmax
  3674. obj.options['ymax'] = ymax
  3675. log.debug("Object changed, updating the bounding box data on self.options")
  3676. # delete the old selection shape
  3677. self.delete_selection_shape()
  3678. self.should_we_save = True
  3679. def on_object_plotted(self):
  3680. """
  3681. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3682. :return: None
  3683. """
  3684. self.on_zoom_fit(None)
  3685. def on_about(self):
  3686. """
  3687. Displays the "about" dialog found in the Menu --> Help.
  3688. :return: None
  3689. """
  3690. self.report_usage("on_about")
  3691. version = self.version
  3692. version_date = self.version_date
  3693. beta = self.beta
  3694. class AboutDialog(QtWidgets.QDialog):
  3695. def __init__(self, parent=None):
  3696. QtWidgets.QDialog.__init__(self, parent)
  3697. # Icon and title
  3698. self.setWindowIcon(parent.app_icon)
  3699. self.setWindowTitle(_("About FlatCAM"))
  3700. self.resize(600, 200)
  3701. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3702. # self.setStyleSheet(
  3703. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3704. # "background-attachment: fixed"
  3705. # )
  3706. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3707. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3708. # palette = QtGui.QPalette()
  3709. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3710. # self.setPalette(palette)
  3711. logo = QtWidgets.QLabel()
  3712. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3713. title = QtWidgets.QLabel(
  3714. "<font size=8><B>FlatCAM</B></font><BR>"
  3715. "{title}<BR>"
  3716. "<BR>"
  3717. "<BR>"
  3718. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3719. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3720. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3721. "<B>{issue}</B></a><BR>".format(
  3722. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3723. devel=_("Development"),
  3724. down=_("DOWNLOAD"),
  3725. issue=_("Issue tracker"))
  3726. )
  3727. title.setOpenExternalLinks(True)
  3728. closebtn = QtWidgets.QPushButton(_("Close"))
  3729. tab_widget = QtWidgets.QTabWidget()
  3730. description_label = QtWidgets.QLabel(
  3731. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3732. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3733. version=version,
  3734. beta=('BETA' if beta else ''),
  3735. date=version_date,
  3736. arch=platform.architecture()[0])
  3737. )
  3738. description_label.setOpenExternalLinks(True)
  3739. lic_lbl_header = QtWidgets.QLabel(
  3740. '%s:<br>%s<br>' % (
  3741. _('Licensed under the MIT license'),
  3742. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3743. "http://www.opensource.org/licenses/mit-license.php</a>"
  3744. )
  3745. )
  3746. lic_lbl_header.setOpenExternalLinks(True)
  3747. lic_lbl_body = QtWidgets.QLabel(
  3748. _(
  3749. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3750. 'of this software and associated documentation files (the "Software"), to deal\n'
  3751. 'in the Software without restriction, including without limitation the rights\n'
  3752. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3753. 'copies of the Software, and to permit persons to whom the Software is\n'
  3754. 'furnished to do so, subject to the following conditions:\n\n'
  3755. 'The above copyright notice and this permission notice shall be included in\n'
  3756. 'all copies or substantial portions of the Software.\n\n'
  3757. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3758. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3759. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3760. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3761. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3762. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3763. 'THE SOFTWARE.'
  3764. )
  3765. )
  3766. attributions_label = QtWidgets.QLabel(
  3767. _(
  3768. 'Some of the icons used are from the following sources:<br>'
  3769. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3770. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3771. 'title="Flaticon">www.flaticon.com</a></div>'
  3772. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3773. )
  3774. )
  3775. # layouts
  3776. layout1 = QtWidgets.QVBoxLayout()
  3777. layout1_1 = QtWidgets.QHBoxLayout()
  3778. layout1_2 = QtWidgets.QHBoxLayout()
  3779. layout2 = QtWidgets.QHBoxLayout()
  3780. layout3 = QtWidgets.QHBoxLayout()
  3781. self.setLayout(layout1)
  3782. layout1.addLayout(layout1_1)
  3783. layout1.addLayout(layout1_2)
  3784. layout1.addLayout(layout2)
  3785. layout1.addLayout(layout3)
  3786. layout1_1.addStretch()
  3787. layout1_1.addWidget(description_label)
  3788. layout1_2.addWidget(tab_widget)
  3789. self.splash_tab = QtWidgets.QWidget()
  3790. self.splash_tab.setObjectName("splash_about")
  3791. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3792. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3793. tab_widget.addTab(self.splash_tab, _("Splash"))
  3794. self.programmmers_tab = QtWidgets.QWidget()
  3795. self.programmmers_tab.setObjectName("programmers_about")
  3796. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3797. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3798. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3799. self.translators_tab = QtWidgets.QWidget()
  3800. self.translators_tab.setObjectName("translators_about")
  3801. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3802. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3803. tab_widget.addTab(self.translators_tab, _("Translators"))
  3804. self.license_tab = QtWidgets.QWidget()
  3805. self.license_tab.setObjectName("license_about")
  3806. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3807. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3808. tab_widget.addTab(self.license_tab, _("License"))
  3809. self.attributions_tab = QtWidgets.QWidget()
  3810. self.attributions_tab.setObjectName("attributions_about")
  3811. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3812. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3813. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3814. self.splash_tab_layout.addWidget(logo, stretch=0)
  3815. self.splash_tab_layout.addWidget(title, stretch=1)
  3816. pal = QtGui.QPalette()
  3817. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3818. self.prog_grid_lay = QtWidgets.QGridLayout()
  3819. self.prog_grid_lay.setHorizontalSpacing(20)
  3820. self.prog_grid_lay.setColumnStretch(0, 0)
  3821. self.prog_grid_lay.setColumnStretch(2, 1)
  3822. prog_widget = QtWidgets.QWidget()
  3823. prog_widget.setLayout(self.prog_grid_lay)
  3824. prog_scroll = QtWidgets.QScrollArea()
  3825. prog_scroll.setWidget(prog_widget)
  3826. prog_scroll.setWidgetResizable(True)
  3827. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3828. prog_scroll.setPalette(pal)
  3829. self.programmmers_tab_layout.addWidget(prog_scroll)
  3830. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3831. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3832. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3833. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3834. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3835. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3836. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3837. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3838. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3839. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3840. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3841. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3842. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3843. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3844. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3845. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3846. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3847. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3848. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3849. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3850. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3851. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3852. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3853. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3854. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3855. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3856. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3857. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3858. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3859. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3860. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3861. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3862. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3863. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3864. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3865. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3866. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3867. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3868. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3869. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3870. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3871. self.translator_grid_lay = QtWidgets.QGridLayout()
  3872. self.translator_grid_lay.setColumnStretch(0, 0)
  3873. self.translator_grid_lay.setColumnStretch(1, 0)
  3874. self.translator_grid_lay.setColumnStretch(2, 1)
  3875. self.translator_grid_lay.setColumnStretch(3, 0)
  3876. # trans_widget = QtWidgets.QWidget()
  3877. # trans_widget.setLayout(self.translator_grid_lay)
  3878. # self.translators_tab_layout.addWidget(trans_widget)
  3879. # self.translators_tab_layout.addStretch()
  3880. trans_widget = QtWidgets.QWidget()
  3881. trans_widget.setLayout(self.translator_grid_lay)
  3882. trans_scroll = QtWidgets.QScrollArea()
  3883. trans_scroll.setWidget(trans_widget)
  3884. trans_scroll.setWidgetResizable(True)
  3885. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3886. trans_scroll.setPalette(pal)
  3887. self.translators_tab_layout.addWidget(trans_scroll)
  3888. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3889. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3890. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3891. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3892. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3893. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3894. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3895. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3896. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3897. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3898. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3899. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3900. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3901. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3902. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3903. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3904. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3905. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3906. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3907. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3908. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3909. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3910. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3911. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3912. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3913. self.translator_grid_lay.setColumnStretch(0, 0)
  3914. self.translators_tab_layout.addStretch()
  3915. self.license_tab_layout.addWidget(lic_lbl_header)
  3916. self.license_tab_layout.addWidget(lic_lbl_body)
  3917. self.license_tab_layout.addStretch()
  3918. self.attributions_tab_layout.addWidget(attributions_label)
  3919. self.attributions_tab_layout.addStretch()
  3920. layout3.addStretch()
  3921. layout3.addWidget(closebtn)
  3922. closebtn.clicked.connect(self.accept)
  3923. AboutDialog(self.ui).exec_()
  3924. def install_bookmarks(self, book_dict=None):
  3925. """
  3926. Install the bookmarks actions in the Help menu -> Bookmarks
  3927. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3928. :return: None
  3929. """
  3930. if book_dict is None:
  3931. self.defaults["global_bookmarks"].update(
  3932. {
  3933. '1': ['FlatCAM', "http://flatcam.org"],
  3934. '2': ['Backup Site', ""]
  3935. }
  3936. )
  3937. else:
  3938. self.defaults["global_bookmarks"].clear()
  3939. self.defaults["global_bookmarks"].update(book_dict)
  3940. # first try to disconnect if somehow they get connected from elsewhere
  3941. for act in self.ui.menuhelp_bookmarks.actions():
  3942. try:
  3943. act.triggered.disconnect()
  3944. except TypeError:
  3945. pass
  3946. # clear all actions except the last one who is the Bookmark manager
  3947. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3948. pass
  3949. else:
  3950. self.ui.menuhelp_bookmarks.removeAction(act)
  3951. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3952. if self.defaults["global_bookmarks"]:
  3953. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3954. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3955. # the JSON is first making the keys as strings (therefore I have to use strings too
  3956. # or do the conversion :(
  3957. # )
  3958. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3959. # the '10' entry jsut after '1' therefore ordering as strings
  3960. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3961. key=lambda x: int(x[0]))
  3962. for entry, bookmark in sorted_bookmarks:
  3963. title = bookmark[0]
  3964. weblink = bookmark[1]
  3965. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3966. act.setText(title)
  3967. act.setIcon(QtGui.QIcon('share/link16.png'))
  3968. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3969. if title == 'Backup Site' and weblink == "":
  3970. act.triggered.connect(self.on_backup_site)
  3971. else:
  3972. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3973. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3974. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3975. def on_bookmarks_manager(self):
  3976. """
  3977. Adds the bookmark manager in a Tab in Plot Area
  3978. :return:
  3979. """
  3980. for idx in range(self.ui.plot_tab_area.count()):
  3981. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3982. # there can be only one instance of Bookmark Manager at one time
  3983. return
  3984. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3985. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3986. # add the tab if it was closed
  3987. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3988. # delete the absolute and relative position and messages in the infobar
  3989. self.ui.position_label.setText("")
  3990. self.ui.rel_position_label.setText("")
  3991. # Switch plot_area to preferences page
  3992. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3993. @staticmethod
  3994. def on_backup_site():
  3995. msgbox = QtWidgets.QMessageBox()
  3996. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3997. "1. FlatCAM.org website is down\n"
  3998. "2. Someone forked FlatCAM project and wants to point\n"
  3999. "to his own website\n\n"
  4000. "If you can't get any informations about FlatCAM beta\n"
  4001. "use the YouTube channel link from the Help menu."))
  4002. msgbox.setWindowTitle(_("Alternative website"))
  4003. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  4004. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4005. msgbox.setDefaultButton(bt_yes)
  4006. msgbox.exec_()
  4007. # response = msgbox.clickedButton()
  4008. def on_file_savedefaults(self):
  4009. """
  4010. Callback for menu item File->Save Defaults. Saves application default options
  4011. ``self.defaults`` to current_defaults.FlatConfig.
  4012. :return: None
  4013. """
  4014. self.save_defaults()
  4015. # def on_app_exit(self):
  4016. # self.report_usage("on_app_exit()")
  4017. #
  4018. # if self.collection.get_list():
  4019. # msgbox = QtWidgets.QMessageBox()
  4020. # # msgbox.setText("<B>Save changes ...</B>")
  4021. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4022. # "\n"
  4023. # "Do you want to Save the project?")
  4024. # msgbox.setWindowTitle("Save changes")
  4025. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4026. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4027. # QtWidgets.QMessageBox.Cancel)
  4028. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4029. #
  4030. # response = msgbox.exec_()
  4031. #
  4032. # if response == QtWidgets.QMessageBox.Yes:
  4033. # self.on_file_saveprojectas(thread=False)
  4034. # elif response == QtWidgets.QMessageBox.Cancel:
  4035. # return
  4036. # self.save_defaults()
  4037. # else:
  4038. # self.save_defaults()
  4039. # log.debug("Application defaults saved ... Exit event.")
  4040. # QtWidgets.qApp.quit()
  4041. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4042. """
  4043. Saves application default options
  4044. ``self.defaults`` to current_defaults.FlatConfig file.
  4045. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4046. used at the next launch of the application.
  4047. :param silent: whether to display a message in status bar or not; boolean
  4048. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4049. When the application is portable it should be a mobile location.
  4050. :return: None
  4051. """
  4052. self.report_usage("save_defaults")
  4053. if data_path is None:
  4054. data_path = self.data_path
  4055. # Read options from file
  4056. try:
  4057. f = open(data_path + "/current_defaults.FlatConfig")
  4058. defaults_file_content = f.read()
  4059. f.close()
  4060. except Exception:
  4061. e = sys.exc_info()[0]
  4062. App.log.error("Could not load defaults file.")
  4063. App.log.error(str(e))
  4064. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4065. return
  4066. try:
  4067. defaults = json.loads(defaults_file_content)
  4068. except Exception:
  4069. e = sys.exc_info()[0]
  4070. App.log.error("Failed to parse defaults file.")
  4071. App.log.error(str(e))
  4072. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4073. return
  4074. # Update options
  4075. self.defaults_read_form()
  4076. defaults.update(self.defaults)
  4077. self.propagate_defaults(silent=True)
  4078. # Save the toolbar view
  4079. tb_status = 0
  4080. if self.ui.toolbarfile.isVisible():
  4081. tb_status += 1
  4082. if self.ui.toolbargeo.isVisible():
  4083. tb_status += 2
  4084. if self.ui.toolbarview.isVisible():
  4085. tb_status += 4
  4086. if self.ui.toolbartools.isVisible():
  4087. tb_status += 8
  4088. if self.ui.exc_edit_toolbar.isVisible():
  4089. tb_status += 16
  4090. if self.ui.geo_edit_toolbar.isVisible():
  4091. tb_status += 32
  4092. if self.ui.grb_edit_toolbar.isVisible():
  4093. tb_status += 64
  4094. if self.ui.snap_toolbar.isVisible():
  4095. tb_status += 128
  4096. if self.ui.toolbarshell.isVisible():
  4097. tb_status += 256
  4098. if first_time is False:
  4099. self.defaults["global_toolbar_view"] = tb_status
  4100. # Save update options
  4101. try:
  4102. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4103. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4104. f.close()
  4105. except Exception as e:
  4106. log.debug("App.save_defaults() --> %s" % str(e))
  4107. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4108. return
  4109. if not silent:
  4110. self.inform.emit('[success] %s' % _("Preferences saved."))
  4111. def save_factory_defaults(self, silent_message=False, data_path=None):
  4112. """
  4113. Saves application factory default options
  4114. ``self.defaults`` to factory_defaults.FlatConfig.
  4115. It's a one time job done just after the first install.
  4116. :param silent_message: whether to display a message in status bar or not; boolean
  4117. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4118. When the application is portable it should be a mobile location.
  4119. :return: None
  4120. """
  4121. self.report_usage("save_factory_defaults")
  4122. if data_path is None:
  4123. data_path = self.data_path
  4124. # Read options from file
  4125. try:
  4126. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4127. factory_defaults_file_content = f_f_def.read()
  4128. f_f_def.close()
  4129. except Exception:
  4130. e = sys.exc_info()[0]
  4131. App.log.error("Could not load factory defaults file.")
  4132. App.log.error(str(e))
  4133. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4134. return
  4135. try:
  4136. factory_defaults = json.loads(factory_defaults_file_content)
  4137. except Exception:
  4138. e = sys.exc_info()[0]
  4139. App.log.error("Failed to parse factory defaults file.")
  4140. App.log.error(str(e))
  4141. if silent_message is False:
  4142. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4143. return
  4144. # Update options
  4145. self.defaults_read_form()
  4146. factory_defaults.update(self.defaults)
  4147. self.propagate_defaults(silent=True)
  4148. # Save update options
  4149. try:
  4150. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4151. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4152. f_f_def_s.close()
  4153. except Exception as e:
  4154. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4155. if silent_message is False:
  4156. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4157. return
  4158. if silent_message is False:
  4159. self.inform.emit(_("Factory defaults saved."))
  4160. def final_save(self):
  4161. """
  4162. Callback for doing a preferences save to file whenever the application is about to quit.
  4163. If the project has changes, it will ask the user to save the project.
  4164. :return: None
  4165. """
  4166. if self.save_in_progress:
  4167. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4168. return
  4169. if self.should_we_save and self.collection.get_list():
  4170. msgbox = QtWidgets.QMessageBox()
  4171. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4172. "\n"
  4173. "Do you want to Save the project?"))
  4174. msgbox.setWindowTitle(_("Save changes"))
  4175. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4176. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4177. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4178. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4179. msgbox.setDefaultButton(bt_yes)
  4180. msgbox.exec_()
  4181. response = msgbox.clickedButton()
  4182. if response == bt_yes:
  4183. try:
  4184. self.trayIcon.hide()
  4185. except Exception:
  4186. pass
  4187. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4188. elif response == bt_no:
  4189. try:
  4190. self.trayIcon.hide()
  4191. except Exception:
  4192. pass
  4193. self.quit_application()
  4194. elif response == bt_cancel:
  4195. return
  4196. else:
  4197. try:
  4198. self.trayIcon.hide()
  4199. except Exception:
  4200. pass
  4201. self.quit_application()
  4202. def quit_application(self):
  4203. """
  4204. Called (as a pyslot or not) when the application is quit.
  4205. :return: None
  4206. """
  4207. self.save_defaults()
  4208. log.debug("App.final_save() --> App Defaults saved.")
  4209. if self.cmd_line_headless != 1:
  4210. # save app state to file
  4211. stgs = QSettings("Open Source", "FlatCAM")
  4212. stgs.setValue('saved_gui_state', self.ui.saveState())
  4213. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4214. stgs.setValue(
  4215. 'language',
  4216. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4217. )
  4218. stgs.setValue(
  4219. 'notebook_font_size',
  4220. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4221. )
  4222. stgs.setValue(
  4223. 'axis_font_size',
  4224. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4225. )
  4226. stgs.setValue(
  4227. 'textbox_font_size',
  4228. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4229. )
  4230. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4231. stgs.setValue(
  4232. 'machinist',
  4233. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4234. )
  4235. # This will write the setting to the platform specific storage.
  4236. del stgs
  4237. log.debug("App.final_save() --> App UI state saved.")
  4238. QtWidgets.qApp.quit()
  4239. def on_portable_checked(self, state):
  4240. """
  4241. Callback called when the checkbox in Preferences GUI is checked.
  4242. It will set the application as portable by creating the preferences and recent files in the
  4243. 'config' folder found in the FlatCAM installation folder.
  4244. :param state: boolean, the state of the checkbox when clicked/checked
  4245. :return:
  4246. """
  4247. line_no = 0
  4248. data = None
  4249. if sys.platform != 'win32':
  4250. # this won't work in Linux or MacOS
  4251. return
  4252. # test if the app was frozen and choose the path for the configuration file
  4253. if getattr(sys, "frozen", False) is True:
  4254. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4255. else:
  4256. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4257. config_file = current_data_path + '\\configuration.txt'
  4258. try:
  4259. with open(config_file, 'r') as f:
  4260. try:
  4261. data = f.readlines()
  4262. except Exception as e:
  4263. log.debug('App.__init__() -->%s' % str(e))
  4264. return
  4265. except FileNotFoundError:
  4266. pass
  4267. for line in data:
  4268. line = line.strip('\n')
  4269. param = str(line).rpartition('=')
  4270. if param[0] == 'portable':
  4271. break
  4272. line_no += 1
  4273. if state:
  4274. data[line_no] = 'portable=True\n'
  4275. # create the new defauults files
  4276. # create current_defaults.FlatConfig file if there is none
  4277. try:
  4278. f = open(current_data_path + '/current_defaults.FlatConfig')
  4279. f.close()
  4280. except IOError:
  4281. App.log.debug('Creating empty current_defaults.FlatConfig')
  4282. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4283. json.dump({}, f)
  4284. f.close()
  4285. # create factory_defaults.FlatConfig file if there is none
  4286. try:
  4287. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4288. f.close()
  4289. except IOError:
  4290. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4291. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4292. json.dump({}, f)
  4293. f.close()
  4294. try:
  4295. f = open(current_data_path + '/recent.json')
  4296. f.close()
  4297. except IOError:
  4298. App.log.debug('Creating empty recent.json')
  4299. f = open(current_data_path + '/recent.json', 'w')
  4300. json.dump([], f)
  4301. f.close()
  4302. try:
  4303. fp = open(current_data_path + '/recent_projects.json')
  4304. fp.close()
  4305. except IOError:
  4306. App.log.debug('Creating empty recent_projects.json')
  4307. fp = open(current_data_path + '/recent_projects.json', 'w')
  4308. json.dump([], fp)
  4309. fp.close()
  4310. # save the current defaults to the new defaults file
  4311. self.save_defaults(silent=True, data_path=current_data_path)
  4312. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4313. else:
  4314. data[line_no] = 'portable=False\n'
  4315. with open(config_file, 'w') as f:
  4316. f.writelines(data)
  4317. def on_toggle_shell(self):
  4318. """
  4319. Toggle shell: if is visible close it, if it is closed then open it
  4320. :return: None
  4321. """
  4322. self.report_usage("on_toggle_shell()")
  4323. if self.ui.shell_dock.isVisible():
  4324. self.ui.shell_dock.hide()
  4325. else:
  4326. self.ui.shell_dock.show()
  4327. def on_register_files(self, obj_type=None):
  4328. """
  4329. Called whenever there is a need to register file extensions with FlatCAM.
  4330. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4331. :param obj_type: the type of object to be register for.
  4332. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4333. :return: None
  4334. """
  4335. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4336. new_reg_path = 'Software\\Classes\\'
  4337. # find if the current user is admin
  4338. try:
  4339. is_admin = os.getuid() == 0
  4340. except AttributeError:
  4341. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4342. if is_admin is True:
  4343. root_path = winreg.HKEY_LOCAL_MACHINE
  4344. else:
  4345. root_path = winreg.HKEY_CURRENT_USER
  4346. # create the keys
  4347. def set_reg(name, root_path, new_reg_path, value):
  4348. try:
  4349. winreg.CreateKey(root_path, new_reg_path)
  4350. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4351. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4352. return True
  4353. except WindowsError:
  4354. return False
  4355. # delete key in registry
  4356. def delete_reg(root_path, reg_path, key_to_del):
  4357. key_to_del_path = reg_path + key_to_del
  4358. try:
  4359. winreg.DeleteKey(root_path, key_to_del_path)
  4360. return True
  4361. except WindowsError:
  4362. return False
  4363. if obj_type is None or obj_type == 'excellon':
  4364. exc_list = \
  4365. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4366. exc_list = [x for x in exc_list if x != '']
  4367. # register all keys in the Preferences window
  4368. for ext in exc_list:
  4369. new_k = new_reg_path + '.%s' % ext
  4370. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4371. # and unregister those that are no longer in the Preferences windows but are in the file
  4372. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4373. if ext not in exc_list:
  4374. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4375. # now write the updated extensions to the self.defaults
  4376. # new_ext = ''
  4377. # for ext in exc_list:
  4378. # new_ext = new_ext + ext + ', '
  4379. # self.defaults["fa_excellon"] = new_ext
  4380. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4381. if obj_type is None or obj_type == 'gcode':
  4382. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4383. gco_list = [x for x in gco_list if x != '']
  4384. # register all keys in the Preferences window
  4385. for ext in gco_list:
  4386. new_k = new_reg_path + '.%s' % ext
  4387. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4388. # and unregister those that are no longer in the Preferences windows but are in the file
  4389. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4390. if ext not in gco_list:
  4391. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4392. # now write the updated extensions to the self.defaults
  4393. # new_ext = ''
  4394. # for ext in gco_list:
  4395. # new_ext = new_ext + ext + ', '
  4396. # self.defaults["fa_gcode"] = new_ext
  4397. self.inform.emit('[success] %s' %
  4398. _("Selected GCode file extensions registered with FlatCAM."))
  4399. if obj_type is None or obj_type == 'gerber':
  4400. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4401. grb_list = [x for x in grb_list if x != '']
  4402. # register all keys in the Preferences window
  4403. for ext in grb_list:
  4404. new_k = new_reg_path + '.%s' % ext
  4405. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4406. # and unregister those that are no longer in the Preferences windows but are in the file
  4407. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4408. if ext not in grb_list:
  4409. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4410. # now write the updated extensions to the self.defaults
  4411. # new_ext = ''
  4412. # for ext in grb_list:
  4413. # new_ext = new_ext + ext + ', '
  4414. # self.defaults["fa_gerber"] = new_ext
  4415. self.inform.emit('[success] %s' %
  4416. _("Selected Gerber file extensions registered with FlatCAM."))
  4417. def add_extension(self, ext_type):
  4418. """
  4419. Add a file extension to the list for a specific object
  4420. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4421. :return:
  4422. """
  4423. if ext_type == 'excellon':
  4424. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4425. if new_ext == '':
  4426. return
  4427. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4428. if new_ext in old_val:
  4429. return
  4430. old_val.append(new_ext)
  4431. old_val.sort()
  4432. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4433. if ext_type == 'gcode':
  4434. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4435. if new_ext == '':
  4436. return
  4437. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4438. if new_ext in old_val:
  4439. return
  4440. old_val.append(new_ext)
  4441. old_val.sort()
  4442. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4443. if ext_type == 'gerber':
  4444. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4445. if new_ext == '':
  4446. return
  4447. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4448. if new_ext in old_val:
  4449. return
  4450. old_val.append(new_ext)
  4451. old_val.sort()
  4452. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4453. if ext_type == 'keyword':
  4454. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4455. if new_kw == '':
  4456. return
  4457. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4458. if new_kw in old_val:
  4459. return
  4460. old_val.append(new_kw)
  4461. old_val.sort()
  4462. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4463. # update the self.myKeywords so the model is updated
  4464. self.autocomplete_kw_list = \
  4465. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4466. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4467. self.shell._edit.set_model_data(self.myKeywords)
  4468. def del_extension(self, ext_type):
  4469. """
  4470. Remove a file extension from the list for a specific object
  4471. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4472. :return:
  4473. """
  4474. if ext_type == 'excellon':
  4475. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4476. if new_ext == '':
  4477. return
  4478. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4479. if new_ext not in old_val:
  4480. return
  4481. old_val.remove(new_ext)
  4482. old_val.sort()
  4483. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4484. if ext_type == 'gcode':
  4485. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4486. if new_ext == '':
  4487. return
  4488. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4489. if new_ext not in old_val:
  4490. return
  4491. old_val.remove(new_ext)
  4492. old_val.sort()
  4493. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4494. if ext_type == 'gerber':
  4495. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4496. if new_ext == '':
  4497. return
  4498. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4499. if new_ext not in old_val:
  4500. return
  4501. old_val.remove(new_ext)
  4502. old_val.sort()
  4503. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4504. if ext_type == 'keyword':
  4505. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4506. if new_kw == '':
  4507. return
  4508. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4509. if new_kw not in old_val:
  4510. return
  4511. old_val.remove(new_kw)
  4512. old_val.sort()
  4513. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4514. # update the self.myKeywords so the model is updated
  4515. self.autocomplete_kw_list = \
  4516. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4517. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4518. self.shell._edit.set_model_data(self.myKeywords)
  4519. def restore_extensions(self, ext_type):
  4520. """
  4521. Restore all file extensions associations with FlatCAM, for a specific object
  4522. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4523. :return:
  4524. """
  4525. if ext_type == 'excellon':
  4526. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4527. # for the ability to open Excellon files with .txt extension
  4528. new_exc_list = deepcopy(self.exc_list)
  4529. try:
  4530. new_exc_list.remove('txt')
  4531. except ValueError:
  4532. pass
  4533. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4534. if ext_type == 'gcode':
  4535. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4536. if ext_type == 'gerber':
  4537. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4538. if ext_type == 'keyword':
  4539. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4540. # update the self.myKeywords so the model is updated
  4541. self.autocomplete_kw_list = self.default_keywords
  4542. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4543. self.shell._edit.set_model_data(self.myKeywords)
  4544. def delete_all_extensions(self, ext_type):
  4545. """
  4546. Delete all file extensions associations with FlatCAM, for a specific object
  4547. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4548. :return:
  4549. """
  4550. if ext_type == 'excellon':
  4551. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4552. if ext_type == 'gcode':
  4553. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4554. if ext_type == 'gerber':
  4555. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4556. if ext_type == 'keyword':
  4557. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4558. # update the self.myKeywords so the model is updated
  4559. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4560. self.shell._edit.set_model_data(self.myKeywords)
  4561. def on_edit_join(self, name=None):
  4562. """
  4563. Callback for Edit->Join. Joins the selected geometry objects into
  4564. a new one.
  4565. :return: None
  4566. """
  4567. self.report_usage("on_edit_join()")
  4568. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4569. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4570. geo_type_set = set()
  4571. objs = self.collection.get_selected()
  4572. if len(objs) < 2:
  4573. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4574. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4575. return 'fail'
  4576. for obj in objs:
  4577. geo_type_set.add(obj.multigeo)
  4578. # if len(geo_type_list) == 1 means that all list elements are the same
  4579. if len(geo_type_set) != 1:
  4580. self.inform.emit('[ERROR] %s' %
  4581. _("Failed join. The Geometry objects are of different types.\n"
  4582. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4583. "convert from one to another and retry joining \n"
  4584. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4585. "the result may not be what was expected. \n"
  4586. "Check the generated GCODE."))
  4587. return
  4588. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4589. if True in geo_type_set:
  4590. def initialize(geo_obj, app):
  4591. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4592. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4593. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4594. for v in obj.tools.values():
  4595. v['data']['name'] = obj_name_multi
  4596. self.new_object("geometry", obj_name_multi, initialize)
  4597. else:
  4598. def initialize(geo_obj, app):
  4599. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4600. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4601. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4602. for v in obj.tools.values():
  4603. v['data']['name'] = obj_name_single
  4604. self.new_object("geometry", obj_name_single, initialize)
  4605. self.should_we_save = True
  4606. def on_edit_join_exc(self):
  4607. """
  4608. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4609. a new Excellon.
  4610. :return: None
  4611. """
  4612. self.report_usage("on_edit_join_exc()")
  4613. objs = self.collection.get_selected()
  4614. for obj in objs:
  4615. if not isinstance(obj, FlatCAMExcellon):
  4616. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4617. return
  4618. if len(objs) < 2:
  4619. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4620. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4621. return 'fail'
  4622. def initialize(exc_obj, app):
  4623. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4624. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4625. self.new_object("excellon", 'Combo_Excellon', initialize)
  4626. self.should_we_save = True
  4627. def on_edit_join_grb(self):
  4628. """
  4629. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4630. a new Gerber object.
  4631. :return: None
  4632. """
  4633. self.report_usage("on_edit_join_grb()")
  4634. objs = self.collection.get_selected()
  4635. for obj in objs:
  4636. if not isinstance(obj, FlatCAMGerber):
  4637. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4638. return
  4639. if len(objs) < 2:
  4640. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4641. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4642. return 'fail'
  4643. def initialize(grb_obj, app):
  4644. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4645. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4646. self.new_object("gerber", 'Combo_Gerber', initialize)
  4647. self.should_we_save = True
  4648. def on_convert_singlegeo_to_multigeo(self):
  4649. """
  4650. Called for converting a Geometry object from single-geo to multi-geo.
  4651. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4652. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4653. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4654. the solid-geometry of that tool.
  4655. :return: None
  4656. """
  4657. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4658. obj = self.collection.get_active()
  4659. if obj is None:
  4660. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4661. return
  4662. if not isinstance(obj, FlatCAMGeometry):
  4663. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4664. return
  4665. obj.multigeo = True
  4666. for tooluid, dict_value in obj.tools.items():
  4667. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4668. if not isinstance(obj.solid_geometry, list):
  4669. obj.solid_geometry = [obj.solid_geometry]
  4670. obj.solid_geometry[:] = []
  4671. obj.plot()
  4672. self.should_we_save = True
  4673. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4674. def on_convert_multigeo_to_singlegeo(self):
  4675. """
  4676. Called for converting a Geometry object from multi-geo to single-geo.
  4677. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4678. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4679. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4680. the solid-geometry of that tool.
  4681. :return: None
  4682. """
  4683. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4684. obj = self.collection.get_active()
  4685. if obj is None:
  4686. self.inform.emit('[ERROR_NOTCL] %s' %
  4687. _("Failed. Select a Geometry Object and try again."))
  4688. return
  4689. if not isinstance(obj, FlatCAMGeometry):
  4690. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4691. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4692. return
  4693. obj.multigeo = False
  4694. total_solid_geometry = []
  4695. for tooluid, dict_value in obj.tools.items():
  4696. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4697. # clear the original geometry
  4698. dict_value['solid_geometry'][:] = []
  4699. obj.solid_geometry = deepcopy(total_solid_geometry)
  4700. obj.plot()
  4701. self.should_we_save = True
  4702. self.inform.emit('[success] %s' %
  4703. _("A Geometry object was converted to SingleGeo type."))
  4704. def on_defaults_dict_change(self, field):
  4705. """
  4706. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4707. Edit -> Preferences tab window.
  4708. :param field: the key of the self.defaults dictionary that was changed.
  4709. :return: None
  4710. """
  4711. self.defaults_write_form_field(field)
  4712. if field == "units":
  4713. self.set_screen_units(self.defaults['units'])
  4714. def set_screen_units(self, units):
  4715. """
  4716. Set the FlatCAM units on the status bar.
  4717. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4718. :return: None
  4719. """
  4720. self.ui.units_label.setText("[" + units.lower() + "]")
  4721. def on_toggle_units_click(self):
  4722. try:
  4723. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4724. except (TypeError, AttributeError):
  4725. pass
  4726. if self.defaults["units"] == 'MM':
  4727. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4728. else:
  4729. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4730. self.on_toggle_units(no_pref=True)
  4731. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4732. lambda: self.on_toggle_units(no_pref=False))
  4733. def on_toggle_units(self, no_pref=False):
  4734. """
  4735. Callback for the Units radio-button change in the Preferences tab.
  4736. Changes the application's default units adn for the project too.
  4737. If changing the project's units, the change propagates to all of
  4738. the objects in the project.
  4739. :return: None
  4740. """
  4741. self.report_usage("on_toggle_units")
  4742. if self.toggle_units_ignore:
  4743. return
  4744. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4745. # If option is the same, then ignore
  4746. if new_units == self.defaults["units"].upper():
  4747. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4748. return
  4749. # Options to scale
  4750. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4751. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4752. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4753. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4754. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4755. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4756. "excellon_editor_slot_lin_pitch",
  4757. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4758. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4759. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4760. "geometry_feedrate_probe", "geometry_startz",
  4761. 'cncjob_tooldia',
  4762. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4763. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4764. "tools_nccnewdia",
  4765. "tools_2sided_drilldia", "tools_film_boundary",
  4766. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4767. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4768. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4769. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4770. "tools_transform_offset_y",
  4771. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4772. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4773. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4774. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4775. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4776. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4777. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4778. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4779. "tools_fiducials_line_thickness",
  4780. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4781. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4782. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4783. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4784. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4785. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4786. def scale_defaults(sfactor):
  4787. for dim in dimensions:
  4788. if dim == 'excellon_toolchangexy':
  4789. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4790. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4791. coords_xy[0] *= sfactor
  4792. coords_xy[1] *= sfactor
  4793. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4794. self.decimals, coords_xy[1])
  4795. elif dim == 'geometry_toolchangexy':
  4796. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4797. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4798. coords_xy[0] *= sfactor
  4799. coords_xy[1] *= sfactor
  4800. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4801. self.decimals, coords_xy[1])
  4802. elif dim == 'geometry_cnctooldia':
  4803. tools_diameters = []
  4804. try:
  4805. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4806. tools_diameters = [eval(a) for a in tools_string if a != '']
  4807. except Exception as e:
  4808. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4809. self.defaults['geometry_cnctooldia'] = ''
  4810. for t in range(len(tools_diameters)):
  4811. tools_diameters[t] *= sfactor
  4812. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4813. elif dim == 'tools_ncctools':
  4814. ncctools = []
  4815. try:
  4816. tools_string = self.defaults["tools_ncctools"].split(",")
  4817. ncctools = [eval(a) for a in tools_string if a != '']
  4818. except Exception as e:
  4819. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4820. self.defaults['tools_ncctools'] = ''
  4821. for t in range(len(ncctools)):
  4822. ncctools[t] *= sfactor
  4823. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4824. elif dim == 'tools_solderpaste_tools':
  4825. sptools = []
  4826. try:
  4827. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4828. sptools = [eval(a) for a in tools_string if a != '']
  4829. except Exception as e:
  4830. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4831. self.defaults['tools_solderpaste_tools'] = ""
  4832. for t in range(len(sptools)):
  4833. sptools[t] *= sfactor
  4834. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4835. elif dim == 'tools_solderpaste_xy_toolchange':
  4836. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4837. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4838. sp_coords[0] *= sfactor
  4839. sp_coords[1] *= sfactor
  4840. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4841. self.decimals, sp_coords[1])
  4842. elif dim == 'global_gridx' or dim == 'global_gridy':
  4843. if new_units == 'IN':
  4844. val = 0.1
  4845. try:
  4846. val = float(self.defaults[dim]) * sfactor
  4847. except Exception as e:
  4848. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4849. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4850. else:
  4851. val = 0.1
  4852. try:
  4853. val = float(self.defaults[dim]) * sfactor
  4854. except Exception as e:
  4855. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4856. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4857. else:
  4858. val = 0.1
  4859. if self.defaults[dim]:
  4860. try:
  4861. val = float(self.defaults[dim]) * sfactor
  4862. except Exception as e:
  4863. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4864. self.defaults[dim] = val
  4865. # The scaling factor depending on choice of units.
  4866. factor = 25.4 if new_units == 'MM' else 1/25.4
  4867. # Changing project units. Warn user.
  4868. msgbox = QtWidgets.QMessageBox()
  4869. msgbox.setWindowTitle(_("Toggle Units"))
  4870. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4871. msgbox.setText(_("Changing the units of the project\n"
  4872. "will scale all objects.\n\n"
  4873. "Do you want to continue?"))
  4874. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4875. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4876. msgbox.setDefaultButton(bt_ok)
  4877. msgbox.exec_()
  4878. response = msgbox.clickedButton()
  4879. if response == bt_ok:
  4880. if no_pref is False:
  4881. self.defaults_read_form()
  4882. scale_defaults(factor)
  4883. self.defaults_write_form(fl_units=new_units)
  4884. self.defaults["units"] = new_units
  4885. # update the defaults from form, some may assume that the conversion is enough and it's not
  4886. self.on_options_app2project()
  4887. # update the objects
  4888. for obj in self.collection.get_list():
  4889. obj.convert_units(new_units)
  4890. # make that the properties stored in the object are also updated
  4891. self.object_changed.emit(obj)
  4892. # rebuild the object UI
  4893. obj.build_ui()
  4894. # change this only if the workspace is active
  4895. if self.defaults['global_workspace'] is True:
  4896. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4897. # adjust the grid values on the main toolbar
  4898. val_x = float(self.defaults['global_gridx']) * factor
  4899. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4900. current = self.collection.get_active()
  4901. if current is not None:
  4902. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4903. if not isinstance(current, FlatCAMGeometry):
  4904. current.to_form()
  4905. # replot all objects
  4906. self.plot_all()
  4907. # set the status labels to reflect the current FlatCAM units
  4908. self.set_screen_units(new_units)
  4909. # signal to the app that we changed the object properties and it shoud save the project
  4910. self.should_we_save = True
  4911. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4912. else:
  4913. # Undo toggling
  4914. self.toggle_units_ignore = True
  4915. if self.defaults['units'].upper() == 'MM':
  4916. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4917. else:
  4918. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4919. self.toggle_units_ignore = False
  4920. # store the grid values so they are not changed in the next step
  4921. val_x = float(self.defaults['global_gridx'])
  4922. val_y = float(self.defaults['global_gridy'])
  4923. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  4924. self.defaults_read_form()
  4925. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4926. # I don't want it for the grid values, so I update them here
  4927. self.defaults['global_gridx'] = val_x
  4928. self.defaults['global_gridy'] = val_y
  4929. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4930. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4931. def on_fullscreen(self, disable=False):
  4932. self.report_usage("on_fullscreen()")
  4933. if self.toggle_fscreen is False and disable is False:
  4934. # self.ui.showFullScreen()
  4935. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4936. a = self.ui.geometry()
  4937. self.x_pos = a.x()
  4938. self.y_pos = a.y()
  4939. self.width = a.width()
  4940. self.height = a.height()
  4941. # set new geometry to full desktop rect
  4942. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4943. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4944. # everything else will not work without this hack. This happen in Windows.
  4945. # https://bugreports.qt.io/browse/QTBUG-41309
  4946. desktop = QtWidgets.QApplication.desktop()
  4947. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4948. rec = desktop.screenGeometry(screen)
  4949. x = rec.x() - 1
  4950. y = rec.y() - 1
  4951. h = rec.height() + 2
  4952. w = rec.width() + 2
  4953. self.ui.setGeometry(x, y, w, h)
  4954. self.ui.show()
  4955. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4956. tb.setVisible(False)
  4957. self.ui.splitter_left.setVisible(False)
  4958. self.toggle_fscreen = True
  4959. elif self.toggle_fscreen is True or disable is True:
  4960. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4961. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4962. self.ui.showNormal()
  4963. self.restore_toolbar_view()
  4964. self.ui.splitter_left.setVisible(True)
  4965. self.toggle_fscreen = False
  4966. def on_toggle_plotarea(self):
  4967. self.report_usage("on_toggle_plotarea()")
  4968. try:
  4969. name = self.ui.plot_tab_area.widget(0).objectName()
  4970. except AttributeError:
  4971. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4972. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4973. self.ui.plot_tab_area.protectTab(0)
  4974. return
  4975. if name != 'plotarea':
  4976. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4977. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4978. self.ui.plot_tab_area.protectTab(0)
  4979. else:
  4980. self.ui.plot_tab_area.closeTab(0)
  4981. def on_toggle_notebook(self):
  4982. if self.ui.splitter.sizes()[0] == 0:
  4983. self.ui.splitter.setSizes([1, 1])
  4984. self.ui.menu_toggle_nb.setChecked(True)
  4985. else:
  4986. self.ui.splitter.setSizes([0, 1])
  4987. self.ui.menu_toggle_nb.setChecked(False)
  4988. def on_toggle_axis(self):
  4989. self.report_usage("on_toggle_axis()")
  4990. if self.toggle_axis is False:
  4991. if self.is_legacy is False:
  4992. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4993. parent=self.plotcanvas.view.scene)
  4994. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4995. parent=self.plotcanvas.view.scene)
  4996. else:
  4997. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4998. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4999. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5000. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5001. self.plotcanvas.canvas.draw()
  5002. self.toggle_axis = True
  5003. else:
  5004. if self.is_legacy is False:
  5005. self.plotcanvas.v_line.parent = None
  5006. self.plotcanvas.h_line.parent = None
  5007. else:
  5008. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5009. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5010. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5011. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5012. self.plotcanvas.canvas.draw()
  5013. self.toggle_axis = False
  5014. def on_toggle_grid(self):
  5015. self.report_usage("on_toggle_grid()")
  5016. self.ui.grid_snap_btn.trigger()
  5017. def on_toggle_grid_lines(self):
  5018. self.report_usage("on_toggle_grd_lines()")
  5019. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5020. if tt_settings.contains("theme"):
  5021. theme = tt_settings.value('theme', type=str)
  5022. else:
  5023. theme = 'white'
  5024. if self.toggle_grid_lines is False:
  5025. if self.is_legacy is False:
  5026. if theme == 'white':
  5027. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5028. else:
  5029. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5030. else:
  5031. self.plotcanvas.axes.grid(True)
  5032. try:
  5033. self.plotcanvas.canvas.draw()
  5034. except IndexError:
  5035. pass
  5036. pass
  5037. self.toggle_grid_lines = True
  5038. else:
  5039. if self.is_legacy is False:
  5040. if theme == 'white':
  5041. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5042. else:
  5043. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5044. else:
  5045. self.plotcanvas.axes.grid(False)
  5046. try:
  5047. self.plotcanvas.canvas.draw()
  5048. except IndexError:
  5049. pass
  5050. self.toggle_grid_lines = False
  5051. if self.is_legacy is False:
  5052. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5053. # - perhaps is a bug in VisPy implementation
  5054. if self.grid_status() is True:
  5055. self.app_cursor.enabled = False
  5056. self.app_cursor.enabled = True
  5057. else:
  5058. self.app_cursor.enabled = True
  5059. self.app_cursor.enabled = False
  5060. def show_preferences_gui(self):
  5061. """
  5062. Called to initialize and show the Preferences GUI
  5063. :return: None
  5064. """
  5065. self.gen_form = self.ui.general_defaults_form
  5066. self.ger_form = self.ui.gerber_defaults_form
  5067. self.exc_form = self.ui.excellon_defaults_form
  5068. self.geo_form = self.ui.geometry_defaults_form
  5069. self.cnc_form = self.ui.cncjob_defaults_form
  5070. self.tools_form = self.ui.tools_defaults_form
  5071. self.tools2_form = self.ui.tools2_defaults_form
  5072. self.fa_form = self.ui.util_defaults_form
  5073. try:
  5074. self.ui.general_scroll_area.takeWidget()
  5075. except Exception:
  5076. self.log.debug("Nothing to remove")
  5077. self.ui.general_scroll_area.setWidget(self.gen_form)
  5078. self.gen_form.show()
  5079. try:
  5080. self.ui.gerber_scroll_area.takeWidget()
  5081. except Exception:
  5082. self.log.debug("Nothing to remove")
  5083. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5084. self.ger_form.show()
  5085. try:
  5086. self.ui.excellon_scroll_area.takeWidget()
  5087. except Exception:
  5088. self.log.debug("Nothing to remove")
  5089. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5090. self.exc_form.show()
  5091. try:
  5092. self.ui.geometry_scroll_area.takeWidget()
  5093. except Exception:
  5094. self.log.debug("Nothing to remove")
  5095. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5096. self.geo_form.show()
  5097. try:
  5098. self.ui.cncjob_scroll_area.takeWidget()
  5099. except Exception:
  5100. self.log.debug("Nothing to remove")
  5101. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5102. self.cnc_form.show()
  5103. try:
  5104. self.ui.tools_scroll_area.takeWidget()
  5105. except Exception:
  5106. self.log.debug("Nothing to remove")
  5107. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5108. self.tools_form.show()
  5109. try:
  5110. self.ui.tools2_scroll_area.takeWidget()
  5111. except Exception:
  5112. self.log.debug("Nothing to remove")
  5113. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5114. self.tools2_form.show()
  5115. try:
  5116. self.ui.fa_scroll_area.takeWidget()
  5117. except Exception:
  5118. self.log.debug("Nothing to remove")
  5119. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5120. self.fa_form.show()
  5121. self.log.debug("Finished Preferences GUI form initialization.")
  5122. # self.options2form()
  5123. def init_color_pickers_in_preferences_gui(self):
  5124. # Init Plot Colors
  5125. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5126. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5127. "background-color:%s;"
  5128. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5129. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5130. int(self.defaults['global_plot_fill'][7:9], 16))
  5131. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5132. int(self.defaults['global_plot_fill'][7:9], 16))
  5133. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5134. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5135. "background-color:%s;"
  5136. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5137. # Init Left-Right Selection colors
  5138. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5139. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5140. "background-color:%s;"
  5141. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5142. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5143. int(self.defaults['global_sel_fill'][7:9], 16))
  5144. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5145. int(self.defaults['global_sel_fill'][7:9], 16))
  5146. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5147. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5148. "background-color:%s;"
  5149. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5150. # Init Right-Left Selection colors
  5151. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5152. self.defaults['global_alt_sel_fill'])
  5153. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5154. "background-color:%s;"
  5155. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5156. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5157. int(self.defaults['global_sel_fill'][7:9], 16))
  5158. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5159. int(self.defaults['global_sel_fill'][7:9], 16))
  5160. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5161. self.defaults['global_alt_sel_line'])
  5162. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5163. "background-color:%s;"
  5164. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5165. # Init Draw color and Selection Draw Color
  5166. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5167. self.defaults['global_draw_color'])
  5168. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5169. "background-color:%s;"
  5170. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5171. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5172. self.defaults['global_sel_draw_color'])
  5173. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5174. "background-color:%s;"
  5175. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5176. # Init Project Items color
  5177. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5178. self.defaults['global_proj_item_color'])
  5179. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5180. "background-color:%s;"
  5181. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5182. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5183. self.defaults['global_proj_item_dis_color'])
  5184. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5185. "background-color:%s;"
  5186. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5187. # Init the Annotation CNC Job color
  5188. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5189. self.defaults['cncjob_annotation_fontcolor'])
  5190. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5191. "background-color:%s;"
  5192. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5193. # Init the Tool Film color
  5194. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5195. self.defaults['tools_film_color'])
  5196. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5197. "background-color:%s;"
  5198. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5199. )
  5200. # Init the Tool QRCode colors
  5201. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5202. self.defaults['tools_qrcode_fill_color'])
  5203. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5204. "background-color:%s;"
  5205. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5206. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5207. self.defaults['tools_qrcode_back_color'])
  5208. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5209. "background-color:%s;"
  5210. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5211. def on_excellon_defaults_button(self):
  5212. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5213. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5214. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5215. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5216. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5217. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5218. log.debug("Excellon app defaults loaded ...")
  5219. def on_update_exc_export(self, state):
  5220. """
  5221. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5222. if the update_excellon_cb checkbox is checked
  5223. :param state: state of the checkbox whose signals is tied to his slot
  5224. :return:
  5225. """
  5226. if state:
  5227. # first try to disconnect
  5228. try:
  5229. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5230. disconnect(self.on_excellon_format_changed)
  5231. except TypeError:
  5232. pass
  5233. try:
  5234. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5235. disconnect(self.on_excellon_format_changed)
  5236. except TypeError:
  5237. pass
  5238. try:
  5239. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5240. disconnect(self.on_excellon_format_changed)
  5241. except TypeError:
  5242. pass
  5243. try:
  5244. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5245. disconnect(self.on_excellon_format_changed)
  5246. except TypeError:
  5247. pass
  5248. try:
  5249. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5250. disconnect(self.on_excellon_zeros_changed)
  5251. except TypeError:
  5252. pass
  5253. try:
  5254. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5255. disconnect(self.on_excellon_zeros_changed)
  5256. except TypeError:
  5257. pass
  5258. # the connect them
  5259. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5260. self.on_excellon_format_changed)
  5261. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5262. self.on_excellon_format_changed)
  5263. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5264. self.on_excellon_format_changed)
  5265. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5266. self.on_excellon_format_changed)
  5267. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5268. self.on_excellon_zeros_changed)
  5269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5270. self.on_excellon_units_changed)
  5271. else:
  5272. # disconnect the signals
  5273. try:
  5274. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5275. disconnect(self.on_excellon_format_changed)
  5276. except TypeError:
  5277. pass
  5278. try:
  5279. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5280. disconnect(self.on_excellon_format_changed)
  5281. except TypeError:
  5282. pass
  5283. try:
  5284. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5285. disconnect(self.on_excellon_format_changed)
  5286. except TypeError:
  5287. pass
  5288. try:
  5289. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5290. disconnect(self.on_excellon_format_changed)
  5291. except TypeError:
  5292. pass
  5293. try:
  5294. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5295. disconnect(self.on_excellon_zeros_changed)
  5296. except TypeError:
  5297. pass
  5298. try:
  5299. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5300. disconnect(self.on_excellon_zeros_changed)
  5301. except TypeError:
  5302. pass
  5303. def on_excellon_format_changed(self):
  5304. """
  5305. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5306. :return: None
  5307. """
  5308. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5309. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5310. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5311. )
  5312. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5313. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5314. )
  5315. else:
  5316. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5317. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5318. )
  5319. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5320. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5321. )
  5322. def on_excellon_zeros_changed(self):
  5323. """
  5324. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5325. :return: None
  5326. """
  5327. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5328. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5329. )
  5330. def on_excellon_units_changed(self):
  5331. """
  5332. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5333. :return: None
  5334. """
  5335. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5336. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5337. )
  5338. self.on_excellon_format_changed()
  5339. # Setting plot colors handlers
  5340. def on_pf_color_entry(self):
  5341. self.defaults['global_plot_fill'] = \
  5342. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5343. self.defaults['global_plot_fill'][7:9]
  5344. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5345. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5346. def on_pf_color_button(self):
  5347. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5348. c_dialog = QtWidgets.QColorDialog()
  5349. plot_fill_color = c_dialog.getColor(initial=current_color)
  5350. if plot_fill_color.isValid() is False:
  5351. return
  5352. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5353. "background-color:%s" % str(plot_fill_color.name()))
  5354. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5355. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5356. self.defaults['global_plot_fill'] = new_val
  5357. def on_pf_color_spinner(self):
  5358. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5359. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5360. self.defaults['global_plot_fill'] = \
  5361. self.defaults['global_plot_fill'][:7] + \
  5362. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5363. self.defaults['global_plot_line'] = \
  5364. self.defaults['global_plot_line'][:7] + \
  5365. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5366. def on_pf_color_slider(self):
  5367. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5368. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5369. def on_pl_color_entry(self):
  5370. self.defaults['global_plot_line'] = \
  5371. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5372. self.defaults['global_plot_line'][7:9]
  5373. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5374. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5375. def on_pl_color_button(self):
  5376. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5377. # print(current_color)
  5378. c_dialog = QtWidgets.QColorDialog()
  5379. plot_line_color = c_dialog.getColor(initial=current_color)
  5380. if plot_line_color.isValid() is False:
  5381. return
  5382. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5383. "background-color:%s" % str(plot_line_color.name()))
  5384. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5385. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5386. self.defaults['global_plot_line'] = new_val_line
  5387. # Setting selection colors (left - right) handlers
  5388. def on_sf_color_entry(self):
  5389. self.defaults['global_sel_fill'] = \
  5390. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5391. self.defaults['global_sel_fill'][7:9]
  5392. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5393. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5394. def on_sf_color_button(self):
  5395. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5396. c_dialog = QtWidgets.QColorDialog()
  5397. plot_fill_color = c_dialog.getColor(initial=current_color)
  5398. if plot_fill_color.isValid() is False:
  5399. return
  5400. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5401. "background-color:%s" % str(plot_fill_color.name()))
  5402. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5403. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5404. self.defaults['global_sel_fill'] = new_val
  5405. def on_sf_color_spinner(self):
  5406. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5407. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5408. self.defaults['global_sel_fill'] = \
  5409. self.defaults['global_sel_fill'][:7] + \
  5410. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5411. self.defaults['global_sel_line'] = \
  5412. self.defaults['global_sel_line'][:7] + \
  5413. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5414. def on_sf_color_slider(self):
  5415. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5416. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5417. def on_sl_color_entry(self):
  5418. self.defaults['global_sel_line'] = \
  5419. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5420. self.defaults['global_sel_line'][7:9]
  5421. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5422. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5423. def on_sl_color_button(self):
  5424. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5425. c_dialog = QtWidgets.QColorDialog()
  5426. plot_line_color = c_dialog.getColor(initial=current_color)
  5427. if plot_line_color.isValid() is False:
  5428. return
  5429. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5430. "background-color:%s" % str(plot_line_color.name()))
  5431. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5432. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5433. self.defaults['global_sel_line'] = new_val_line
  5434. # Setting selection colors (right - left) handlers
  5435. def on_alt_sf_color_entry(self):
  5436. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5437. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5438. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5439. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5440. def on_alt_sf_color_button(self):
  5441. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5442. c_dialog = QtWidgets.QColorDialog()
  5443. plot_fill_color = c_dialog.getColor(initial=current_color)
  5444. if plot_fill_color.isValid() is False:
  5445. return
  5446. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5447. "background-color:%s" % str(plot_fill_color.name()))
  5448. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5449. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5450. self.defaults['global_alt_sel_fill'] = new_val
  5451. def on_alt_sf_color_spinner(self):
  5452. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5453. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5454. self.defaults['global_alt_sel_fill'] = \
  5455. self.defaults['global_alt_sel_fill'][:7] + \
  5456. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5457. self.defaults['global_alt_sel_line'] = \
  5458. self.defaults['global_alt_sel_line'][:7] + \
  5459. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5460. def on_alt_sf_color_slider(self):
  5461. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5462. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5463. def on_alt_sl_color_entry(self):
  5464. self.defaults['global_alt_sel_line'] = \
  5465. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5466. self.defaults['global_alt_sel_line'][7:9]
  5467. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5468. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5469. def on_alt_sl_color_button(self):
  5470. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5471. c_dialog = QtWidgets.QColorDialog()
  5472. plot_line_color = c_dialog.getColor(initial=current_color)
  5473. if plot_line_color.isValid() is False:
  5474. return
  5475. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5476. "background-color:%s" % str(plot_line_color.name()))
  5477. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5478. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5479. self.defaults['global_alt_sel_line'] = new_val_line
  5480. # Setting Editor colors
  5481. def on_draw_color_entry(self):
  5482. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5483. .draw_color_entry.get_value()
  5484. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5485. "background-color:%s" % str(self.defaults['global_draw_color']))
  5486. def on_draw_color_button(self):
  5487. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5488. c_dialog = QtWidgets.QColorDialog()
  5489. draw_color = c_dialog.getColor(initial=current_color)
  5490. if draw_color.isValid() is False:
  5491. return
  5492. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5493. "background-color:%s" % str(draw_color.name()))
  5494. new_val = str(draw_color.name())
  5495. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5496. self.defaults['global_draw_color'] = new_val
  5497. def on_sel_draw_color_entry(self):
  5498. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5499. .sel_draw_color_entry.get_value()
  5500. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5501. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5502. def on_sel_draw_color_button(self):
  5503. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5504. c_dialog = QtWidgets.QColorDialog()
  5505. sel_draw_color = c_dialog.getColor(initial=current_color)
  5506. if sel_draw_color.isValid() is False:
  5507. return
  5508. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5509. "background-color:%s" % str(sel_draw_color.name()))
  5510. new_val_sel = str(sel_draw_color.name())
  5511. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5512. self.defaults['global_sel_draw_color'] = new_val_sel
  5513. def on_proj_color_entry(self):
  5514. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5515. .proj_color_entry.get_value()
  5516. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5517. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5518. def on_proj_color_button(self):
  5519. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5520. c_dialog = QtWidgets.QColorDialog()
  5521. proj_color = c_dialog.getColor(initial=current_color)
  5522. if proj_color.isValid() is False:
  5523. return
  5524. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5525. "background-color:%s" % str(proj_color.name()))
  5526. new_val_sel = str(proj_color.name())
  5527. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5528. self.defaults['global_proj_item_color'] = new_val_sel
  5529. def on_proj_color_dis_entry(self):
  5530. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5531. .proj_color_dis_entry.get_value()
  5532. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5533. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5534. def on_proj_color_dis_button(self):
  5535. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5536. c_dialog = QtWidgets.QColorDialog()
  5537. proj_color = c_dialog.getColor(initial=current_color)
  5538. if proj_color.isValid() is False:
  5539. return
  5540. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5541. "background-color:%s" % str(proj_color.name()))
  5542. new_val_sel = str(proj_color.name())
  5543. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5544. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5545. def on_annotation_fontcolor_entry(self):
  5546. self.defaults['cncjob_annotation_fontcolor'] = \
  5547. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5548. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5549. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5550. def on_annotation_fontcolor_button(self):
  5551. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5552. c_dialog = QtWidgets.QColorDialog()
  5553. annotation_color = c_dialog.getColor(initial=current_color)
  5554. if annotation_color.isValid() is False:
  5555. return
  5556. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5557. "background-color:%s" % str(annotation_color.name()))
  5558. new_val_sel = str(annotation_color.name())
  5559. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5560. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5561. def on_film_color_entry(self):
  5562. self.defaults['tools_film_color'] = \
  5563. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5564. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5565. "background-color:%s;"
  5566. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5567. )
  5568. def on_film_color_button(self):
  5569. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5570. c_dialog = QtWidgets.QColorDialog()
  5571. film_color = c_dialog.getColor(initial=current_color)
  5572. if film_color.isValid() is False:
  5573. return
  5574. # if new color is different then mark that the Preferences are changed
  5575. if film_color != current_color:
  5576. self.on_preferences_edited()
  5577. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5578. "background-color:%s;"
  5579. "border-color: dimgray" % str(film_color.name())
  5580. )
  5581. new_val_sel = str(film_color.name())
  5582. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5583. self.defaults['tools_film_color'] = new_val_sel
  5584. def on_qrcode_fill_color_entry(self):
  5585. self.defaults['tools_qrcode_fill_color'] = \
  5586. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5587. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5588. "background-color:%s;"
  5589. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5590. )
  5591. def on_qrcode_fill_color_button(self):
  5592. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5593. c_dialog = QtWidgets.QColorDialog()
  5594. fill_color = c_dialog.getColor(initial=current_color)
  5595. if fill_color.isValid() is False:
  5596. return
  5597. # if new color is different then mark that the Preferences are changed
  5598. if fill_color != current_color:
  5599. self.on_preferences_edited()
  5600. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5601. "background-color:%s;"
  5602. "border-color: dimgray" % str(fill_color.name())
  5603. )
  5604. new_val_sel = str(fill_color.name())
  5605. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5606. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5607. def on_qrcode_back_color_entry(self):
  5608. self.defaults['tools_qrcode_back_color'] = \
  5609. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5610. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5611. "background-color:%s;"
  5612. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5613. )
  5614. def on_qrcode_back_color_button(self):
  5615. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5616. c_dialog = QtWidgets.QColorDialog()
  5617. back_color = c_dialog.getColor(initial=current_color)
  5618. if back_color.isValid() is False:
  5619. return
  5620. # if new color is different then mark that the Preferences are changed
  5621. if back_color != current_color:
  5622. self.on_preferences_edited()
  5623. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5624. "background-color:%s;"
  5625. "border-color: dimgray" % str(back_color.name())
  5626. )
  5627. new_val_sel = str(back_color.name())
  5628. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5629. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5630. def on_splash_changed(self, state):
  5631. settings = QSettings("Open Source", "FlatCAM")
  5632. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5633. # This will write the setting to the platform specific storage.
  5634. del settings
  5635. def on_tab_rmb_click(self, checked):
  5636. self.ui.notebook.set_detachable(val=checked)
  5637. self.defaults["global_tabs_detachable"] = checked
  5638. self.ui.plot_tab_area.set_detachable(val=checked)
  5639. self.defaults["global_tabs_detachable"] = checked
  5640. def on_tab_setup_context_menu(self):
  5641. initial_checked = self.defaults["global_tabs_detachable"]
  5642. action_name = str(_("Detachable Tabs"))
  5643. action = QtWidgets.QAction(self)
  5644. action.setCheckable(True)
  5645. action.setText(action_name)
  5646. action.setChecked(initial_checked)
  5647. self.ui.notebook.tabBar.addAction(action)
  5648. self.ui.plot_tab_area.tabBar.addAction(action)
  5649. try:
  5650. action.triggered.disconnect()
  5651. except TypeError:
  5652. pass
  5653. action.triggered.connect(self.on_tab_rmb_click)
  5654. def on_deselect_all(self):
  5655. self.collection.set_all_inactive()
  5656. self.delete_selection_shape()
  5657. def on_workspace_modified(self):
  5658. # self.save_defaults(silent=True)
  5659. if self.is_legacy is True:
  5660. self.plotcanvas.delete_workspace()
  5661. self.defaults_read_form()
  5662. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5663. def on_workspace(self):
  5664. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5665. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5666. else:
  5667. self.plotcanvas.delete_workspace()
  5668. self.defaults_read_form()
  5669. # self.save_defaults(silent=True)
  5670. def on_workspace_toggle(self):
  5671. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5672. try:
  5673. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5674. except TypeError:
  5675. pass
  5676. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5677. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5678. self.on_workspace()
  5679. def on_layout(self, index=None, lay=None):
  5680. """
  5681. Set the toolbars layout (location)
  5682. :param index:
  5683. :param lay: type of layout to be set on the toolbard
  5684. :return: None
  5685. """
  5686. self.report_usage("on_layout()")
  5687. if lay:
  5688. current_layout = lay
  5689. else:
  5690. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5691. lay_settings = QSettings("Open Source", "FlatCAM")
  5692. lay_settings.setValue('layout', current_layout)
  5693. # This will write the setting to the platform specific storage.
  5694. del lay_settings
  5695. # first remove the toolbars:
  5696. try:
  5697. self.ui.removeToolBar(self.ui.toolbarfile)
  5698. self.ui.removeToolBar(self.ui.toolbargeo)
  5699. self.ui.removeToolBar(self.ui.toolbarview)
  5700. self.ui.removeToolBar(self.ui.toolbarshell)
  5701. self.ui.removeToolBar(self.ui.toolbartools)
  5702. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5703. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5704. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5705. self.ui.removeToolBar(self.ui.snap_toolbar)
  5706. self.ui.removeToolBar(self.ui.toolbarshell)
  5707. except Exception:
  5708. pass
  5709. if current_layout == 'standard':
  5710. # ## TOOLBAR INSTALLATION # ##
  5711. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5712. self.ui.toolbarfile.setObjectName('File_TB')
  5713. self.ui.addToolBar(self.ui.toolbarfile)
  5714. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5715. self.ui.toolbargeo.setObjectName('Edit_TB')
  5716. self.ui.addToolBar(self.ui.toolbargeo)
  5717. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5718. self.ui.toolbarview.setObjectName('View_TB')
  5719. self.ui.addToolBar(self.ui.toolbarview)
  5720. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5721. self.ui.toolbarshell.setObjectName('Shell_TB')
  5722. self.ui.addToolBar(self.ui.toolbarshell)
  5723. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5724. self.ui.toolbartools.setObjectName('Tools_TB')
  5725. self.ui.addToolBar(self.ui.toolbartools)
  5726. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5727. # self.ui.exc_edit_toolbar.setVisible(False)
  5728. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5729. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5730. self.ui.addToolBarBreak()
  5731. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5732. # self.ui.geo_edit_toolbar.setVisible(False)
  5733. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5734. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5735. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5736. # self.ui.grb_edit_toolbar.setVisible(False)
  5737. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5738. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5739. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5740. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5741. # self.ui.snap_toolbar.setMaximumHeight(30)
  5742. self.ui.addToolBar(self.ui.snap_toolbar)
  5743. self.ui.corner_snap_btn.setVisible(False)
  5744. self.ui.snap_magnet.setVisible(False)
  5745. elif current_layout == 'compact':
  5746. # ## TOOLBAR INSTALLATION # ##
  5747. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5748. self.ui.toolbarfile.setObjectName('File_TB')
  5749. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5750. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5751. self.ui.toolbargeo.setObjectName('Edit_TB')
  5752. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5753. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5754. self.ui.toolbarshell.setObjectName('Shell_TB')
  5755. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5756. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5757. self.ui.toolbartools.setObjectName('Tools_TB')
  5758. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5759. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5760. # self.ui.geo_edit_toolbar.setVisible(False)
  5761. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5762. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5763. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5764. self.ui.toolbarview.setObjectName('View_TB')
  5765. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5766. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5767. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5768. # self.ui.grb_edit_toolbar.setVisible(False)
  5769. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5770. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5771. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5772. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5773. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5774. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5775. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5776. self.ui.snap_toolbar.setMaximumHeight(30)
  5777. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5778. self.ui.corner_snap_btn.setVisible(True)
  5779. self.ui.snap_magnet.setVisible(True)
  5780. # add all the actions to the toolbars
  5781. self.ui.populate_toolbars()
  5782. # reconnect all the signals to the toolbar actions
  5783. self.connect_toolbar_signals()
  5784. self.ui.grid_snap_btn.setChecked(True)
  5785. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5786. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5787. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5788. self.ui.grid_gap_link_cb.setChecked(True)
  5789. def on_cursor_type(self, val):
  5790. """
  5791. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5792. :return: None
  5793. """
  5794. self.app_cursor.enabled = False
  5795. if val == 'small':
  5796. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5797. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5798. self.app_cursor = self.plotcanvas.new_cursor()
  5799. else:
  5800. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5801. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5802. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5803. if self.ui.grid_snap_btn.isChecked():
  5804. self.app_cursor.enabled = True
  5805. else:
  5806. self.app_cursor.enabled = False
  5807. def on_cnc_custom_parameters(self, signal_text):
  5808. if signal_text == 'Parameters':
  5809. return
  5810. else:
  5811. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5812. def on_save_button(self, save_to_file=True):
  5813. log.debug("App.on_save_button() --> Applying preferences to file.")
  5814. # Preferences saved, update flag
  5815. self.preferences_changed_flag = False
  5816. # Preferences save, update the color of the Preferences Tab text
  5817. for idx in range(self.ui.plot_tab_area.count()):
  5818. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5819. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5820. self.inform.emit('%s' % _("Preferences applied."))
  5821. if save_to_file:
  5822. self.save_defaults(silent=False)
  5823. # load the defaults so they are updated into the app
  5824. self.load_defaults(filename='current_defaults')
  5825. # Re-fresh project options
  5826. self.on_options_app2project()
  5827. settgs = QSettings("Open Source", "FlatCAM")
  5828. # save the notebook font size
  5829. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5830. settgs.setValue('notebook_font_size', fsize)
  5831. # save the axis font size
  5832. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5833. settgs.setValue('axis_font_size', g_fsize)
  5834. # save the textbox font size
  5835. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5836. settgs.setValue('textbox_font_size', tb_fsize)
  5837. settgs.setValue(
  5838. 'machinist',
  5839. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5840. )
  5841. # This will write the setting to the platform specific storage.
  5842. del settgs
  5843. def on_pref_close_button(self):
  5844. # Preferences saved, update flag
  5845. self.preferences_changed_flag = False
  5846. try:
  5847. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5848. except TypeError:
  5849. pass
  5850. self.defaults_write_form()
  5851. # Preferences save, update the color of the Preferences Tab text
  5852. for idx in range(self.ui.plot_tab_area.count()):
  5853. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5854. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5855. self.ui.plot_tab_area.closeTab(idx)
  5856. break
  5857. self.inform.emit('%s' % _("Preferences closed without saving."))
  5858. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5859. def on_tool_add_keypress(self):
  5860. # ## Current application units in Upper Case
  5861. self.units = self.defaults['units'].upper()
  5862. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5863. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5864. if notebook_widget_name == 'selected_tab':
  5865. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5866. # Tool add works for Geometry only if Advanced is True in Preferences
  5867. if self.defaults["global_app_level"] == 'a':
  5868. tool_add_popup = FCInputDialog(title="New Tool ...",
  5869. text='Enter a Tool Diameter:',
  5870. min=0.0000, max=99.9999, decimals=4)
  5871. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5872. val, ok = tool_add_popup.get_value()
  5873. if ok:
  5874. if float(val) == 0:
  5875. self.inform.emit('[WARNING_NOTCL] %s' %
  5876. _("Please enter a tool diameter with non-zero value, in Float format."))
  5877. return
  5878. self.collection.get_active().on_tool_add(dia=float(val))
  5879. else:
  5880. self.inform.emit('[WARNING_NOTCL] %s...' %
  5881. _("Adding Tool cancelled"))
  5882. else:
  5883. msgbox = QtWidgets.QMessageBox()
  5884. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5885. "Go to Preferences -> General - Show Advanced Options."))
  5886. msgbox.setWindowTitle("Tool adding ...")
  5887. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5888. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5889. msgbox.setDefaultButton(bt_ok)
  5890. msgbox.exec_()
  5891. # work only if the notebook tab on focus is the Tools_Tab
  5892. if notebook_widget_name == 'tool_tab':
  5893. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5894. # and only if the tool is NCC Tool
  5895. if tool_widget == self.ncclear_tool.toolName:
  5896. self.ncclear_tool.on_add_tool_by_key()
  5897. # and only if the tool is Paint Area Tool
  5898. elif tool_widget == self.paint_tool.toolName:
  5899. self.paint_tool.on_add_tool_by_key()
  5900. # and only if the tool is Solder Paste Dispensing Tool
  5901. elif tool_widget == self.paste_tool.toolName:
  5902. self.paste_tool.on_add_tool_by_key()
  5903. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5904. # See description bellow.
  5905. def on_delete_keypress(self):
  5906. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5907. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5908. if notebook_widget_name == 'selected_tab':
  5909. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5910. self.collection.get_active().on_tool_delete()
  5911. # work only if the notebook tab on focus is the Tools_Tab
  5912. elif notebook_widget_name == 'tool_tab':
  5913. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5914. # and only if the tool is NCC Tool
  5915. if tool_widget == self.ncclear_tool.toolName:
  5916. self.ncclear_tool.on_tool_delete()
  5917. # and only if the tool is Paint Tool
  5918. elif tool_widget == self.paint_tool.toolName:
  5919. self.paint_tool.on_tool_delete()
  5920. # and only if the tool is Solder Paste Dispensing Tool
  5921. elif tool_widget == self.paste_tool.toolName:
  5922. self.paste_tool.on_tool_delete()
  5923. else:
  5924. self.on_delete()
  5925. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5926. # some screens you have to be careful where you hover with your mouse.
  5927. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5928. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5929. # Complicated, I know :)
  5930. def on_delete(self):
  5931. """
  5932. Delete the currently selected FlatCAMObjs.
  5933. :return: None
  5934. """
  5935. self.report_usage("on_delete()")
  5936. response = None
  5937. bt_ok = None
  5938. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5939. # a geometry object before we update it.
  5940. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5941. and self.grb_editor.editor_active is False:
  5942. if self.defaults["global_delete_confirmation"] is True:
  5943. msgbox = QtWidgets.QMessageBox()
  5944. msgbox.setWindowTitle(_("Delete objects"))
  5945. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5946. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5947. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5948. "the selected objects?"))
  5949. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5950. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5951. msgbox.setDefaultButton(bt_ok)
  5952. msgbox.exec_()
  5953. response = msgbox.clickedButton()
  5954. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5955. if self.collection.get_active():
  5956. self.log.debug("App.on_delete()")
  5957. while self.collection.get_active():
  5958. obj_active = self.collection.get_active()
  5959. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5960. if isinstance(obj_active, FlatCAMGerber):
  5961. for el in obj_active.mark_shapes:
  5962. obj_active.mark_shapes[el].clear(update=True)
  5963. obj_active.mark_shapes[el].enabled = False
  5964. # obj_active.mark_shapes[el] = None
  5965. del el
  5966. elif isinstance(obj_active, FlatCAMCNCjob):
  5967. try:
  5968. obj_active.annotation.clear(update=True)
  5969. obj_active.annotation.enabled = False
  5970. except AttributeError:
  5971. pass
  5972. self.delete_first_selected()
  5973. self.inform.emit('%s...' %
  5974. _("Object(s) deleted"))
  5975. # make sure that the selection shape is deleted, too
  5976. self.delete_selection_shape()
  5977. else:
  5978. self.inform.emit(_("Failed. No object(s) selected..."))
  5979. else:
  5980. self.inform.emit(_("Save the work in Editor and try again ..."))
  5981. def delete_first_selected(self):
  5982. # Keep this for later
  5983. try:
  5984. sel_obj = self.collection.get_active()
  5985. name = sel_obj.options["name"]
  5986. isPlotted = sel_obj.options["plot"]
  5987. except AttributeError:
  5988. self.log.debug("Nothing selected for deletion")
  5989. return
  5990. if self.is_legacy is True:
  5991. # Remove plot only if the object was plotted otherwise delaxes will fail
  5992. if isPlotted:
  5993. try:
  5994. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5995. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5996. except Exception as e:
  5997. log.debug("App.delete_first_selected() --> %s" % str(e))
  5998. self.plotcanvas.auto_adjust_axes()
  5999. # Remove from dictionary
  6000. self.collection.delete_active()
  6001. # Clear form
  6002. self.setup_component_editor()
  6003. self.inform.emit('%s: %s' %
  6004. (_("Object deleted"), name))
  6005. def on_set_origin(self):
  6006. """
  6007. Set the origin to the left mouse click position
  6008. :return: None
  6009. """
  6010. # display the message for the user
  6011. # and ask him to click on the desired position
  6012. self.report_usage("on_set_origin()")
  6013. def origin_replot():
  6014. def worker_task():
  6015. with self.proc_container.new('%s...' % _("Plotting")):
  6016. for obj in self.collection.get_list():
  6017. obj.plot()
  6018. self.plotcanvas.fit_view()
  6019. if self.is_legacy:
  6020. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6021. else:
  6022. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6023. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6024. self.inform.emit(_('Click to set the origin ...'))
  6025. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6026. # first disconnect it as it may have been used by something else
  6027. try:
  6028. self.replot_signal.disconnect()
  6029. except TypeError:
  6030. pass
  6031. self.replot_signal[list].connect(origin_replot)
  6032. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6033. """
  6034. :param event:
  6035. :param location:
  6036. :param noplot:
  6037. :param use_thread:
  6038. :return:
  6039. """
  6040. noplot_sig = noplot
  6041. def worker_task():
  6042. with self.proc_container.new(_("Setting Origin...")):
  6043. for obj in self.collection.get_list():
  6044. obj.offset((x, y))
  6045. self.object_changed.emit(obj)
  6046. # Update the object bounding box options
  6047. a, b, c, d = obj.bounds()
  6048. obj.options['xmin'] = a
  6049. obj.options['ymin'] = b
  6050. obj.options['xmax'] = c
  6051. obj.options['ymax'] = d
  6052. self.inform.emit('[success] %s...' %
  6053. _('Origin set'))
  6054. if noplot_sig is False:
  6055. self.replot_signal.emit([])
  6056. if location is not None:
  6057. if len(location) != 2:
  6058. self.inform.emit('[ERROR_NOTCL] %s...' %
  6059. _("Origin coordinates specified but incomplete."))
  6060. return 'fail'
  6061. x, y = location
  6062. if use_thread is True:
  6063. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6064. else:
  6065. worker_task()
  6066. self.should_we_save = True
  6067. return
  6068. if event.button == 1:
  6069. if self.is_legacy is False:
  6070. event_pos = event.pos
  6071. else:
  6072. event_pos = (event.xdata, event.ydata)
  6073. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6074. if self.grid_status() == True:
  6075. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6076. else:
  6077. pos = pos_canvas
  6078. x = 0 - pos[0]
  6079. y = 0 - pos[1]
  6080. if use_thread is True:
  6081. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6082. else:
  6083. worker_task()
  6084. self.should_we_save = True
  6085. def on_jump_to(self, custom_location=None, fit_center=True):
  6086. """
  6087. Jump to a location by setting the mouse cursor location
  6088. :return:
  6089. """
  6090. self.report_usage("on_jump_to()")
  6091. # if self.is_legacy is True:
  6092. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6093. # return
  6094. if not custom_location:
  6095. dia_box_location = None
  6096. try:
  6097. dia_box_location = eval(self.clipboard.text())
  6098. except Exception:
  6099. pass
  6100. if type(dia_box_location) == tuple:
  6101. dia_box_location = str(dia_box_location)
  6102. else:
  6103. dia_box_location = None
  6104. dia_box = Dialog_box(title=_("Jump to ..."),
  6105. label=_("Enter the coordinates in format X,Y:"),
  6106. icon=QtGui.QIcon('share/jump_to16.png'),
  6107. initial_text=dia_box_location)
  6108. if dia_box.ok is True:
  6109. try:
  6110. location = eval(dia_box.location)
  6111. if not isinstance(location, tuple):
  6112. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6113. return
  6114. except Exception:
  6115. return
  6116. else:
  6117. return
  6118. else:
  6119. location = custom_location
  6120. units = self.defaults['units'].upper()
  6121. if fit_center:
  6122. self.plotcanvas.fit_center(loc=location)
  6123. cursor = QtGui.QCursor()
  6124. if self.is_legacy is False:
  6125. # I don't know where those differences come from but they are constant for the current
  6126. # execution of the application and they are multiples of a value around 0.0263mm.
  6127. # In a random way sometimes they are more sometimes they are less
  6128. # if units == 'MM':
  6129. # cal_factor = 0.0263
  6130. # else:
  6131. # cal_factor = 0.0263 / 25.4
  6132. cal_location = (location[0], location[1])
  6133. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6134. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6135. j_pos = (
  6136. int(canvas_origin.x() + round(jump_loc[0])),
  6137. int(canvas_origin.y() + round(jump_loc[1]))
  6138. )
  6139. cursor.setPos(j_pos[0], j_pos[1])
  6140. else:
  6141. # find the canvas origin which is in the top left corner
  6142. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6143. # determine the coordinates for the lowest left point of the canvas
  6144. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6145. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6146. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6147. # canvas) and the point (width, height) is in the top-right location
  6148. loc = self.plotcanvas.axes.transData.transform_point(location)
  6149. j_pos = (
  6150. int(x0 + loc[0]),
  6151. int(y0 - loc[1])
  6152. )
  6153. cursor.setPos(j_pos[0], j_pos[1])
  6154. self.plotcanvas.mouse = [location[0], location[1]]
  6155. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6156. if self.grid_status():
  6157. # Update cursor
  6158. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6159. symbol='++', edge_color=self.cursor_color_3D,
  6160. size=self.defaults["global_cursor_size"])
  6161. # Set the position label
  6162. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6163. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6164. # Set the relative position label
  6165. dx = location[0] - float(self.rel_point1[0])
  6166. dy = location[1] - float(self.rel_point1[1])
  6167. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6168. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6169. self.inform.emit('[success] %s' % _("Done."))
  6170. return location
  6171. def on_copy_object(self):
  6172. self.report_usage("on_copy_object()")
  6173. def initialize(obj_init, app):
  6174. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6175. try:
  6176. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6177. except AttributeError:
  6178. pass
  6179. try:
  6180. obj_init.apertures = deepcopy(obj.apertures)
  6181. except AttributeError:
  6182. pass
  6183. try:
  6184. if obj.tools:
  6185. obj_init.tools = deepcopy(obj.tools)
  6186. except Exception as e:
  6187. log.debug("App.on_copy_object() --> %s" % str(e))
  6188. try:
  6189. obj_init.source_file = deepcopy(obj.source_file)
  6190. except (AttributeError, TypeError):
  6191. pass
  6192. def initialize_excellon(obj_init, app):
  6193. obj_init.source_file = deepcopy(obj.source_file)
  6194. obj_init.tools = deepcopy(obj.tools)
  6195. # drills are offset, so they need to be deep copied
  6196. obj_init.drills = deepcopy(obj.drills)
  6197. # slots are offset, so they need to be deep copied
  6198. obj_init.slots = deepcopy(obj.slots)
  6199. obj_init.create_geometry()
  6200. def initialize_script(obj_init, app_obj):
  6201. obj_init.source_file = deepcopy(obj.source_file)
  6202. def initialize_document(obj_init, app_obj):
  6203. obj_init.source_file = deepcopy(obj.source_file)
  6204. for obj in self.collection.get_selected():
  6205. obj_name = obj.options["name"]
  6206. try:
  6207. if isinstance(obj, FlatCAMExcellon):
  6208. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6209. elif isinstance(obj, FlatCAMGerber):
  6210. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6211. elif isinstance(obj, FlatCAMGeometry):
  6212. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6213. elif isinstance(obj, FlatCAMScript):
  6214. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6215. elif isinstance(obj, FlatCAMDocument):
  6216. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6217. except Exception as e:
  6218. return "Operation failed: %s" % str(e)
  6219. def on_copy_object2(self, custom_name):
  6220. def initialize_geometry(obj_init, app):
  6221. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6222. try:
  6223. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6224. except AttributeError:
  6225. pass
  6226. try:
  6227. obj_init.apertures = deepcopy(obj.apertures)
  6228. except AttributeError:
  6229. pass
  6230. try:
  6231. if obj.tools:
  6232. obj_init.tools = deepcopy(obj.tools)
  6233. except Exception as ee:
  6234. log.debug("on_copy_object2() --> %s" % str(ee))
  6235. def initialize_gerber(obj_init, app):
  6236. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6237. obj_init.apertures = deepcopy(obj.apertures)
  6238. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6239. def initialize_excellon(obj_init, app):
  6240. obj_init.tools = deepcopy(obj.tools)
  6241. # drills are offset, so they need to be deep copied
  6242. obj_init.drills = deepcopy(obj.drills)
  6243. # slots are offset, so they need to be deep copied
  6244. obj_init.slots = deepcopy(obj.slots)
  6245. obj_init.create_geometry()
  6246. for obj in self.collection.get_selected():
  6247. obj_name = obj.options["name"]
  6248. try:
  6249. if isinstance(obj, FlatCAMExcellon):
  6250. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6251. elif isinstance(obj, FlatCAMGerber):
  6252. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6253. elif isinstance(obj, FlatCAMGeometry):
  6254. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6255. except Exception as e:
  6256. return "Operation failed: %s" % str(e)
  6257. def on_rename_object(self, text):
  6258. self.report_usage("on_rename_object()")
  6259. named_obj = self.collection.get_active()
  6260. for obj in named_obj:
  6261. if obj is list:
  6262. self.on_rename_object(text)
  6263. else:
  6264. try:
  6265. obj.options['name'] = text
  6266. except Exception as e:
  6267. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6268. def convert_any2geo(self):
  6269. self.report_usage("convert_any2geo()")
  6270. def initialize(obj_init, app):
  6271. obj_init.solid_geometry = obj.solid_geometry
  6272. try:
  6273. obj_init.follow_geometry = obj.follow_geometry
  6274. except AttributeError:
  6275. pass
  6276. try:
  6277. obj_init.apertures = obj.apertures
  6278. except AttributeError:
  6279. pass
  6280. try:
  6281. if obj.tools:
  6282. obj_init.tools = obj.tools
  6283. except AttributeError:
  6284. pass
  6285. def initialize_excellon(obj_init, app):
  6286. # objs = self.collection.get_selected()
  6287. # FlatCAMGeometry.merge(objs, obj)
  6288. solid_geo = []
  6289. for tool in obj.tools:
  6290. for geo in obj.tools[tool]['solid_geometry']:
  6291. solid_geo.append(geo)
  6292. obj_init.solid_geometry = deepcopy(solid_geo)
  6293. if not self.collection.get_selected():
  6294. log.warning("App.convert_any2geo --> No object selected")
  6295. self.inform.emit('[WARNING_NOTCL] %s' %
  6296. _("No object is selected. Select an object and try again."))
  6297. return
  6298. for obj in self.collection.get_selected():
  6299. obj_name = obj.options["name"]
  6300. try:
  6301. if isinstance(obj, FlatCAMExcellon):
  6302. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6303. else:
  6304. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6305. except Exception as e:
  6306. return "Operation failed: %s" % str(e)
  6307. def convert_any2gerber(self):
  6308. self.report_usage("convert_any2gerber()")
  6309. def initialize_geometry(obj_init, app):
  6310. apertures = {}
  6311. apid = 0
  6312. apertures[str(apid)] = {}
  6313. apertures[str(apid)]['geometry'] = []
  6314. for obj_orig in obj.solid_geometry:
  6315. new_elem = dict()
  6316. new_elem['solid'] = obj_orig
  6317. try:
  6318. new_elem['follow'] = obj_orig.exterior
  6319. except AttributeError:
  6320. pass
  6321. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6322. apertures[str(apid)]['size'] = 0.0
  6323. apertures[str(apid)]['type'] = 'C'
  6324. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6325. obj_init.apertures = deepcopy(apertures)
  6326. def initialize_excellon(obj_init, app):
  6327. apertures = {}
  6328. apid = 10
  6329. for tool in obj.tools:
  6330. apertures[str(apid)] = {}
  6331. apertures[str(apid)]['geometry'] = []
  6332. for geo in obj.tools[tool]['solid_geometry']:
  6333. new_el = dict()
  6334. new_el['solid'] = geo
  6335. new_el['follow'] = geo.exterior
  6336. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6337. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6338. apertures[str(apid)]['type'] = 'C'
  6339. apid += 1
  6340. # create solid_geometry
  6341. solid_geometry = []
  6342. for apid in apertures:
  6343. for geo_el in apertures[apid]['geometry']:
  6344. solid_geometry.append(geo_el['solid'])
  6345. solid_geometry = MultiPolygon(solid_geometry)
  6346. solid_geometry = solid_geometry.buffer(0.0000001)
  6347. obj_init.solid_geometry = deepcopy(solid_geometry)
  6348. obj_init.apertures = deepcopy(apertures)
  6349. # clear the working objects (perhaps not necessary due of Python GC)
  6350. apertures.clear()
  6351. if not self.collection.get_selected():
  6352. log.warning("App.convert_any2gerber --> No object selected")
  6353. self.inform.emit('[WARNING_NOTCL] %s' %
  6354. _("No object is selected. Select an object and try again."))
  6355. return
  6356. for obj in self.collection.get_selected():
  6357. obj_name = obj.options["name"]
  6358. try:
  6359. if isinstance(obj, FlatCAMExcellon):
  6360. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6361. elif isinstance(obj, FlatCAMGeometry):
  6362. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6363. else:
  6364. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6365. except Exception as e:
  6366. return "Operation failed: %s" % str(e)
  6367. def abort_all_tasks(self):
  6368. if self.abort_flag is False:
  6369. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6370. self.abort_flag = True
  6371. def app_is_idle(self):
  6372. if self.abort_flag:
  6373. self.inform.emit('[WARNING_NOTCL] %s' %
  6374. _("The current task was gracefully closed on user request..."))
  6375. self.abort_flag = False
  6376. def on_selectall(self):
  6377. self.report_usage("on_selectall()")
  6378. # delete the possible selection box around a possible selected object
  6379. self.delete_selection_shape()
  6380. for name in self.collection.get_names():
  6381. self.collection.set_active(name)
  6382. curr_sel_obj = self.collection.get_by_name(name)
  6383. # create the selection box around the selected object
  6384. if self.defaults['global_selection_shape'] is True:
  6385. self.draw_selection_shape(curr_sel_obj)
  6386. def on_preferences(self):
  6387. """
  6388. Adds the Preferences in a Tab in Plot Area
  6389. :return:
  6390. """
  6391. # add the tab if it was closed
  6392. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6393. # delete the absolute and relative position and messages in the infobar
  6394. self.ui.position_label.setText("")
  6395. self.ui.rel_position_label.setText("")
  6396. # Switch plot_area to preferences page
  6397. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6398. # self.ui.show()
  6399. # detect changes in the preferences
  6400. for idx in range(self.ui.pref_tab_area.count()):
  6401. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6402. try:
  6403. try:
  6404. tb.textEdited.disconnect(self.on_preferences_edited)
  6405. except (TypeError, AttributeError):
  6406. pass
  6407. tb.textEdited.connect(self.on_preferences_edited)
  6408. except AttributeError:
  6409. pass
  6410. try:
  6411. try:
  6412. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6413. except (TypeError, AttributeError):
  6414. pass
  6415. tb.modificationChanged.connect(self.on_preferences_edited)
  6416. except AttributeError:
  6417. pass
  6418. try:
  6419. try:
  6420. tb.toggled.disconnect(self.on_preferences_edited)
  6421. except (TypeError, AttributeError):
  6422. pass
  6423. tb.toggled.connect(self.on_preferences_edited)
  6424. except AttributeError:
  6425. pass
  6426. try:
  6427. try:
  6428. tb.valueChanged.disconnect(self.on_preferences_edited)
  6429. except (TypeError, AttributeError):
  6430. pass
  6431. tb.valueChanged.connect(self.on_preferences_edited)
  6432. except AttributeError:
  6433. pass
  6434. try:
  6435. try:
  6436. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6437. except (TypeError, AttributeError):
  6438. pass
  6439. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6440. except AttributeError:
  6441. pass
  6442. def on_preferences_edited(self):
  6443. self.inform.emit('[WARNING_NOTCL] %s' %
  6444. _("Preferences edited but not saved."))
  6445. for idx in range(self.ui.plot_tab_area.count()):
  6446. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6447. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6448. self.preferences_changed_flag = True
  6449. def on_tools_database(self):
  6450. """
  6451. Adds the Tools Database in a Tab in Plot Area
  6452. :return:
  6453. """
  6454. for idx in range(self.ui.plot_tab_area.count()):
  6455. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6456. # there can be only one instance of Tools Database at one time
  6457. return
  6458. self.tools_db_tab = ToolsDB(
  6459. app=self,
  6460. parent=self.ui,
  6461. callback_on_edited=self.on_tools_db_edited,
  6462. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6463. )
  6464. # add the tab if it was closed
  6465. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6466. self.tools_db_tab.setObjectName("database_tab")
  6467. # delete the absolute and relative position and messages in the infobar
  6468. self.ui.position_label.setText("")
  6469. self.ui.rel_position_label.setText("")
  6470. # Switch plot_area to preferences page
  6471. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6472. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6473. self.tools_db_tab.ui_connect()
  6474. def on_tools_db_edited(self):
  6475. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6476. for idx in range(self.ui.plot_tab_area.count()):
  6477. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6478. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6479. self.tools_db_changed_flag = True
  6480. def on_geometry_tool_add_from_db_executed(self, tool):
  6481. """
  6482. Here add the tool from DB in the selected geometry object
  6483. :return:
  6484. """
  6485. tool_from_db = deepcopy(tool)
  6486. obj = self.collection.get_active()
  6487. if isinstance(obj, FlatCAMGeometry):
  6488. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6489. for idx in range(self.ui.plot_tab_area.count()):
  6490. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6491. wdg = self.ui.plot_tab_area.widget(idx)
  6492. wdg.deleteLater()
  6493. self.ui.plot_tab_area.removeTab(idx)
  6494. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6495. else:
  6496. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6497. def on_plot_area_tab_closed(self, title):
  6498. if title == _("Preferences"):
  6499. # disconnect
  6500. for idx in range(self.ui.pref_tab_area.count()):
  6501. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6502. try:
  6503. tb.textEdited.disconnect(self.on_preferences_edited)
  6504. except (TypeError, AttributeError):
  6505. pass
  6506. try:
  6507. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6508. except (TypeError, AttributeError):
  6509. pass
  6510. try:
  6511. tb.toggled.disconnect(self.on_preferences_edited)
  6512. except (TypeError, AttributeError):
  6513. pass
  6514. try:
  6515. tb.valueChanged.disconnect(self.on_preferences_edited)
  6516. except (TypeError, AttributeError):
  6517. pass
  6518. try:
  6519. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6520. except (TypeError, AttributeError):
  6521. pass
  6522. if self.preferences_changed_flag is True:
  6523. msgbox = QtWidgets.QMessageBox()
  6524. msgbox.setText(_("One or more values are changed.\n"
  6525. "Do you want to save the Preferences?"))
  6526. msgbox.setWindowTitle(_("Save Preferences"))
  6527. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6528. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6529. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6530. msgbox.setDefaultButton(bt_yes)
  6531. msgbox.exec_()
  6532. response = msgbox.clickedButton()
  6533. if response == bt_yes:
  6534. self.on_save_button(save_to_file=True)
  6535. self.inform.emit('[success] %s' % _("Preferences saved."))
  6536. else:
  6537. self.preferences_changed_flag = False
  6538. self.inform.emit('')
  6539. return
  6540. if title == _("Tools Database"):
  6541. # disconnect the signals from the table widget in tab
  6542. self.tools_db_tab.ui_disconnect()
  6543. if self.tools_db_changed_flag is True:
  6544. msgbox = QtWidgets.QMessageBox()
  6545. msgbox.setText(_("One or more Tools are edited.\n"
  6546. "Do you want to update the Tools Database?"))
  6547. msgbox.setWindowTitle(_("Save Tools Database"))
  6548. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6549. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6550. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6551. msgbox.setDefaultButton(bt_yes)
  6552. msgbox.exec_()
  6553. response = msgbox.clickedButton()
  6554. if response == bt_yes:
  6555. self.tools_db_tab.on_save_tools_db()
  6556. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6557. else:
  6558. self.tools_db_changed_flag = False
  6559. self.inform.emit('')
  6560. return
  6561. self.tools_db_tab.deleteLater()
  6562. if title == _("Code Editor"):
  6563. self.toggle_codeeditor = False
  6564. if title == _("Bookmarks Manager"):
  6565. self.book_dialog_tab.rebuild_actions()
  6566. self.book_dialog_tab.deleteLater()
  6567. def on_flipy(self):
  6568. self.report_usage("on_flipy()")
  6569. obj_list = self.collection.get_selected()
  6570. xminlist = []
  6571. yminlist = []
  6572. xmaxlist = []
  6573. ymaxlist = []
  6574. if not obj_list:
  6575. self.inform.emit('[WARNING_NOTCL] %s' %
  6576. _("No object selected to Flip on Y axis."))
  6577. else:
  6578. try:
  6579. # first get a bounding box to fit all
  6580. for obj in obj_list:
  6581. xmin, ymin, xmax, ymax = obj.bounds()
  6582. xminlist.append(xmin)
  6583. yminlist.append(ymin)
  6584. xmaxlist.append(xmax)
  6585. ymaxlist.append(ymax)
  6586. # get the minimum x,y and maximum x,y for all objects selected
  6587. xminimal = min(xminlist)
  6588. yminimal = min(yminlist)
  6589. xmaximal = max(xmaxlist)
  6590. ymaximal = max(ymaxlist)
  6591. px = 0.5 * (xminimal + xmaximal)
  6592. py = 0.5 * (yminimal + ymaximal)
  6593. # execute mirroring
  6594. for obj in obj_list:
  6595. obj.mirror('X', [px, py])
  6596. obj.plot()
  6597. self.object_changed.emit(obj)
  6598. self.inform.emit('[success] %s' %
  6599. _("Flip on Y axis done."))
  6600. except Exception as e:
  6601. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6602. return
  6603. def on_flipx(self):
  6604. self.report_usage("on_flipx()")
  6605. obj_list = self.collection.get_selected()
  6606. xminlist = []
  6607. yminlist = []
  6608. xmaxlist = []
  6609. ymaxlist = []
  6610. if not obj_list:
  6611. self.inform.emit('[WARNING_NOTCL] %s' %
  6612. _("No object selected to Flip on X axis."))
  6613. else:
  6614. try:
  6615. # first get a bounding box to fit all
  6616. for obj in obj_list:
  6617. xmin, ymin, xmax, ymax = obj.bounds()
  6618. xminlist.append(xmin)
  6619. yminlist.append(ymin)
  6620. xmaxlist.append(xmax)
  6621. ymaxlist.append(ymax)
  6622. # get the minimum x,y and maximum x,y for all objects selected
  6623. xminimal = min(xminlist)
  6624. yminimal = min(yminlist)
  6625. xmaximal = max(xmaxlist)
  6626. ymaximal = max(ymaxlist)
  6627. px = 0.5 * (xminimal + xmaximal)
  6628. py = 0.5 * (yminimal + ymaximal)
  6629. # execute mirroring
  6630. for obj in obj_list:
  6631. obj.mirror('Y', [px, py])
  6632. obj.plot()
  6633. self.object_changed.emit(obj)
  6634. self.inform.emit('[success] %s' %
  6635. _("Flip on X axis done."))
  6636. except Exception as e:
  6637. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6638. return
  6639. def on_rotate(self, silent=False, preset=None):
  6640. self.report_usage("on_rotate()")
  6641. obj_list = self.collection.get_selected()
  6642. xminlist = []
  6643. yminlist = []
  6644. xmaxlist = []
  6645. ymaxlist = []
  6646. if not obj_list:
  6647. self.inform.emit('[WARNING_NOTCL] %s' %
  6648. _("No object selected to Rotate."))
  6649. else:
  6650. if silent is False:
  6651. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6652. min=-360, max=360, decimals=4,
  6653. init_val=float(self.defaults['tools_transform_rotate']))
  6654. num, ok = rotatebox.get_value()
  6655. else:
  6656. num = preset
  6657. ok = True
  6658. if ok:
  6659. try:
  6660. # first get a bounding box to fit all
  6661. for obj in obj_list:
  6662. xmin, ymin, xmax, ymax = obj.bounds()
  6663. xminlist.append(xmin)
  6664. yminlist.append(ymin)
  6665. xmaxlist.append(xmax)
  6666. ymaxlist.append(ymax)
  6667. # get the minimum x,y and maximum x,y for all objects selected
  6668. xminimal = min(xminlist)
  6669. yminimal = min(yminlist)
  6670. xmaximal = max(xmaxlist)
  6671. ymaximal = max(ymaxlist)
  6672. px = 0.5 * (xminimal + xmaximal)
  6673. py = 0.5 * (yminimal + ymaximal)
  6674. for sel_obj in obj_list:
  6675. sel_obj.rotate(-float(num), point=(px, py))
  6676. sel_obj.plot()
  6677. self.object_changed.emit(sel_obj)
  6678. self.inform.emit('[success] %s' %
  6679. _("Rotation done."))
  6680. except Exception as e:
  6681. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6682. return
  6683. def on_skewx(self):
  6684. self.report_usage("on_skewx()")
  6685. obj_list = self.collection.get_selected()
  6686. xminlist = []
  6687. yminlist = []
  6688. if not obj_list:
  6689. self.inform.emit('[WARNING_NOTCL] %s' %
  6690. _("No object selected to Skew/Shear on X axis."))
  6691. else:
  6692. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6693. min=-360, max=360, decimals=4,
  6694. init_val=float(self.defaults['tools_transform_skew_x']))
  6695. num, ok = skewxbox.get_value()
  6696. if ok:
  6697. # first get a bounding box to fit all
  6698. for obj in obj_list:
  6699. xmin, ymin, xmax, ymax = obj.bounds()
  6700. xminlist.append(xmin)
  6701. yminlist.append(ymin)
  6702. # get the minimum x,y and maximum x,y for all objects selected
  6703. xminimal = min(xminlist)
  6704. yminimal = min(yminlist)
  6705. for obj in obj_list:
  6706. obj.skew(num, 0, point=(xminimal, yminimal))
  6707. obj.plot()
  6708. self.object_changed.emit(obj)
  6709. self.inform.emit('[success] %s' %
  6710. _("Skew on X axis done."))
  6711. def on_skewy(self):
  6712. self.report_usage("on_skewy()")
  6713. obj_list = self.collection.get_selected()
  6714. xminlist = []
  6715. yminlist = []
  6716. if not obj_list:
  6717. self.inform.emit('[WARNING_NOTCL] %s' %
  6718. _("No object selected to Skew/Shear on Y axis."))
  6719. else:
  6720. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6721. min=-360, max=360, decimals=4,
  6722. init_val=float(self.defaults['tools_transform_skew_y']))
  6723. num, ok = skewybox.get_value()
  6724. if ok:
  6725. # first get a bounding box to fit all
  6726. for obj in obj_list:
  6727. xmin, ymin, xmax, ymax = obj.bounds()
  6728. xminlist.append(xmin)
  6729. yminlist.append(ymin)
  6730. # get the minimum x,y and maximum x,y for all objects selected
  6731. xminimal = min(xminlist)
  6732. yminimal = min(yminlist)
  6733. for obj in obj_list:
  6734. obj.skew(0, num, point=(xminimal, yminimal))
  6735. obj.plot()
  6736. self.object_changed.emit(obj)
  6737. self.inform.emit('[success] %s' %
  6738. _("Skew on Y axis done."))
  6739. def on_plots_updated(self):
  6740. """
  6741. Callback used to report when the plots have changed.
  6742. Adjust axes and zooms to fit.
  6743. :return: None
  6744. """
  6745. if self.is_legacy is False:
  6746. self.plotcanvas.update() # TODO: Need update canvas?
  6747. else:
  6748. self.plotcanvas.auto_adjust_axes()
  6749. self.on_zoom_fit(None)
  6750. self.collection.update_view()
  6751. # self.inform.emit(_("Plots updated ..."))
  6752. # TODO: Rework toolbar 'clear', 'replot' functions
  6753. def on_toolbar_replot(self):
  6754. """
  6755. Callback for toolbar button. Re-plots all objects.
  6756. :return: None
  6757. """
  6758. self.report_usage("on_toolbar_replot")
  6759. self.log.debug("on_toolbar_replot()")
  6760. try:
  6761. self.collection.get_active().read_form()
  6762. except AttributeError:
  6763. self.log.debug("on_toolbar_replot(): AttributeError")
  6764. pass
  6765. self.plot_all()
  6766. def on_row_activated(self, index):
  6767. if index.isValid():
  6768. if index.internalPointer().parent_item != self.collection.root_item:
  6769. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6770. self.collection.on_item_activated(index)
  6771. def on_row_selected(self, obj_name):
  6772. # this is a special string; when received it will make all entries unchecked
  6773. # it mean we clicked outside of the items and deselected all
  6774. if obj_name == 'none':
  6775. for act in self.ui.menuobjects.actions():
  6776. act.setChecked(False)
  6777. return
  6778. # get the name of the selected objects and add them to a list
  6779. name_list = list()
  6780. for obj in self.collection.get_selected():
  6781. name_list.append(obj.options['name'])
  6782. # set all actions as unchecked but the ones selected make them checked
  6783. for act in self.ui.menuobjects.actions():
  6784. act.setChecked(False)
  6785. if act.text() in name_list:
  6786. act.setChecked(True)
  6787. def on_collection_updated(self, obj, state, old_name):
  6788. """
  6789. Create a menu from the object loaded in the collection.
  6790. TODO: should use the collection model to do this
  6791. :param obj: object that was changd (added, deleted, renamed)
  6792. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6793. :param old_name: the old name of the object before the action that triggered this slot happened
  6794. :return: None
  6795. """
  6796. icon_files = {
  6797. "gerber": "share/flatcam_icon16.png",
  6798. "excellon": "share/drill16.png",
  6799. "cncjob": "share/cnc16.png",
  6800. "geometry": "share/geometry16.png",
  6801. "script": "share/script_new16.png",
  6802. "document": "share/notes16_1.png"
  6803. }
  6804. if state == 'append':
  6805. for act in self.ui.menuobjects.actions():
  6806. try:
  6807. act.triggered.disconnect()
  6808. except TypeError:
  6809. pass
  6810. self.ui.menuobjects.clear()
  6811. gerber_list = list()
  6812. exc_list = list()
  6813. cncjob_list = list()
  6814. geo_list = list()
  6815. script_list = list()
  6816. doc_list = list()
  6817. for name in self.collection.get_names():
  6818. obj_named = self.collection.get_by_name(name)
  6819. if obj_named.kind == 'gerber':
  6820. gerber_list.append(name)
  6821. elif obj_named.kind == 'excellon':
  6822. exc_list.append(name)
  6823. elif obj_named.kind == 'cncjob':
  6824. cncjob_list.append(name)
  6825. elif obj_named.kind == 'geometry':
  6826. geo_list.append(name)
  6827. elif obj_named.kind == 'script':
  6828. script_list.append(name)
  6829. elif obj_named.kind == 'document':
  6830. doc_list.append(name)
  6831. def add_act(o_name):
  6832. obj_for_icon = self.collection.get_by_name(o_name)
  6833. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6834. add_action.setCheckable(True)
  6835. add_action.setText(o_name)
  6836. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6837. add_action.triggered.connect(
  6838. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6839. self.collection.set_inactive(o_name))
  6840. self.ui.menuobjects.addAction(add_action)
  6841. for name in gerber_list:
  6842. add_act(name)
  6843. self.ui.menuobjects.addSeparator()
  6844. for name in exc_list:
  6845. add_act(name)
  6846. self.ui.menuobjects.addSeparator()
  6847. for name in cncjob_list:
  6848. add_act(name)
  6849. self.ui.menuobjects.addSeparator()
  6850. for name in geo_list:
  6851. add_act(name)
  6852. self.ui.menuobjects.addSeparator()
  6853. for name in script_list:
  6854. add_act(name)
  6855. self.ui.menuobjects.addSeparator()
  6856. for name in doc_list:
  6857. add_act(name)
  6858. self.ui.menuobjects.addSeparator()
  6859. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6860. QtGui.QIcon('share/select_all.png'),
  6861. _('Select All')
  6862. )
  6863. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6864. QtGui.QIcon('share/deselect_all32.png'),
  6865. _('Deselect All')
  6866. )
  6867. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6868. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6869. elif state == 'delete':
  6870. for act in self.ui.menuobjects.actions():
  6871. if act.text() == obj.options['name']:
  6872. try:
  6873. act.triggered.disconnect()
  6874. except TypeError:
  6875. pass
  6876. self.ui.menuobjects.removeAction(act)
  6877. break
  6878. elif state == 'rename':
  6879. for act in self.ui.menuobjects.actions():
  6880. if act.text() == old_name:
  6881. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6882. add_action.setText(obj.options['name'])
  6883. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6884. add_action.triggered.connect(
  6885. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6886. self.collection.set_inactive(obj.options['name']))
  6887. self.ui.menuobjects.insertAction(act, add_action)
  6888. try:
  6889. act.triggered.disconnect()
  6890. except TypeError:
  6891. pass
  6892. self.ui.menuobjects.removeAction(act)
  6893. break
  6894. elif state == 'delete_all':
  6895. for act in self.ui.menuobjects.actions():
  6896. try:
  6897. act.triggered.disconnect()
  6898. except TypeError:
  6899. pass
  6900. self.ui.menuobjects.clear()
  6901. self.ui.menuobjects.addSeparator()
  6902. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6903. QtGui.QIcon('share/select_all.png'),
  6904. _('Select All')
  6905. )
  6906. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6907. QtGui.QIcon('share/deselect_all32.png'),
  6908. _('Deselect All')
  6909. )
  6910. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6911. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6912. def on_objects_selection(self, on_off):
  6913. obj_list = self.collection.get_names()
  6914. if on_off is True:
  6915. self.collection.set_all_active()
  6916. for act in self.ui.menuobjects.actions():
  6917. try:
  6918. act.setChecked(True)
  6919. except Exception:
  6920. pass
  6921. if obj_list:
  6922. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6923. else:
  6924. self.collection.set_all_inactive()
  6925. for act in self.ui.menuobjects.actions():
  6926. try:
  6927. act.setChecked(False)
  6928. except Exception:
  6929. pass
  6930. if obj_list:
  6931. self.inform.emit('%s' % _("Objects selection is cleared."))
  6932. else:
  6933. self.inform.emit('')
  6934. def grid_status(self):
  6935. if self.ui.grid_snap_btn.isChecked():
  6936. return True
  6937. else:
  6938. return False
  6939. def populate_cmenu_grids(self):
  6940. units = self.defaults['units'].lower()
  6941. self.ui.cmenu_gridmenu.clear()
  6942. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6943. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6944. grid_toggle.setCheckable(True)
  6945. if self.grid_status() == True:
  6946. grid_toggle.setChecked(True)
  6947. else:
  6948. grid_toggle.setChecked(False)
  6949. self.ui.cmenu_gridmenu.addSeparator()
  6950. for grid in sorted_list:
  6951. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6952. action.triggered.connect(self.set_grid)
  6953. self.ui.cmenu_gridmenu.addSeparator()
  6954. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6955. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6956. grid_add.triggered.connect(self.on_grid_add)
  6957. grid_delete.triggered.connect(self.on_grid_delete)
  6958. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6959. def set_grid(self):
  6960. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6961. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6962. def on_grid_add(self):
  6963. # ## Current application units in lower Case
  6964. units = self.defaults['units'].lower()
  6965. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6966. text=_('Enter a Grid Value:'),
  6967. min=0.0000, max=99.9999, decimals=4)
  6968. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6969. val, ok = grid_add_popup.get_value()
  6970. if ok:
  6971. if float(val) == 0:
  6972. self.inform.emit('[WARNING_NOTCL] %s' %
  6973. _("Please enter a grid value with non-zero value, in Float format."))
  6974. return
  6975. else:
  6976. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6977. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6978. self.inform.emit('[success] %s...' %
  6979. _("New Grid added"))
  6980. else:
  6981. self.inform.emit('[WARNING_NOTCL] %s...' %
  6982. _("Grid already exists"))
  6983. else:
  6984. self.inform.emit('[WARNING_NOTCL] %s...' %
  6985. _("Adding New Grid cancelled"))
  6986. def on_grid_delete(self):
  6987. # ## Current application units in lower Case
  6988. units = self.defaults['units'].lower()
  6989. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6990. text='Enter a Grid Value:',
  6991. min=0.0000, max=99.9999, decimals=4)
  6992. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6993. val, ok = grid_del_popup.get_value()
  6994. if ok:
  6995. if float(val) == 0:
  6996. self.inform.emit('[WARNING_NOTCL] %s' %
  6997. _("Please enter a grid value with non-zero value, in Float format."))
  6998. return
  6999. else:
  7000. try:
  7001. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7002. except ValueError:
  7003. self.inform.emit('[ERROR_NOTCL]%s...' %
  7004. _(" Grid Value does not exist"))
  7005. return
  7006. self.inform.emit('[success] %s...' %
  7007. _("Grid Value deleted"))
  7008. else:
  7009. self.inform.emit('[WARNING_NOTCL] %s...' %
  7010. _("Delete Grid value cancelled"))
  7011. def on_shortcut_list(self):
  7012. self.report_usage("on_shortcut_list()")
  7013. # add the tab if it was closed
  7014. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7015. # delete the absolute and relative position and messages in the infobar
  7016. self.ui.position_label.setText("")
  7017. self.ui.rel_position_label.setText("")
  7018. # Switch plot_area to preferences page
  7019. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7020. # self.ui.show()
  7021. def on_select_tab(self, name):
  7022. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7023. if self.ui.splitter.sizes()[0] == 0:
  7024. self.ui.splitter.setSizes([1, 1])
  7025. else:
  7026. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7027. self.ui.splitter.setSizes([0, 1])
  7028. if name == 'project':
  7029. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7030. elif name == 'selected':
  7031. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7032. elif name == 'tool':
  7033. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7034. def on_copy_name(self):
  7035. self.report_usage("on_copy_name()")
  7036. obj = self.collection.get_active()
  7037. try:
  7038. name = obj.options["name"]
  7039. except AttributeError:
  7040. log.debug("on_copy_name() --> No object selected to copy it's name")
  7041. self.inform.emit('[WARNING_NOTCL]%s' %
  7042. _(" No object selected to copy it's name"))
  7043. return
  7044. self.clipboard.setText(name)
  7045. self.inform.emit(_("Name copied on clipboard ..."))
  7046. def on_mouse_click_over_plot(self, event):
  7047. """
  7048. Default actions are:
  7049. :param event: Contains information about the event, like which button
  7050. was clicked, the pixel coordinates and the axes coordinates.
  7051. :return: None
  7052. """
  7053. self.pos = list()
  7054. if self.is_legacy is False:
  7055. event_pos = event.pos
  7056. pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7057. # Set the mouse button for panning
  7058. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7059. else:
  7060. event_pos = (event.xdata, event.ydata)
  7061. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7062. pan_button = 3 if self.defaults["global_pan_button"] == '2'else 2
  7063. # So it can receive key presses
  7064. self.plotcanvas.native.setFocus()
  7065. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7066. if self.grid_status() == True:
  7067. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7068. else:
  7069. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7070. try:
  7071. if event.button == 1:
  7072. # Reset here the relative coordinates so there is a new reference on the click position
  7073. if self.rel_point1 is None:
  7074. self.rel_point1 = self.pos
  7075. else:
  7076. self.rel_point2 = copy(self.rel_point1)
  7077. self.rel_point1 = self.pos
  7078. self.on_mouse_move_over_plot(event, origin_click=True)
  7079. except Exception as e:
  7080. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7081. def on_mouse_double_click_over_plot(self, event):
  7082. if event.button == 1:
  7083. self.doubleclick = True
  7084. def on_mouse_move_over_plot(self, event, origin_click=None):
  7085. """
  7086. Callback for the mouse motion event over the plot.
  7087. :param event: Contains information about the event.
  7088. :param origin_click
  7089. :return: None
  7090. """
  7091. if self.is_legacy is False:
  7092. event_pos = event.pos
  7093. if self.defaults["global_pan_button"] == '2':
  7094. pan_button = 2
  7095. else:
  7096. pan_button = 3
  7097. self.event_is_dragging = event.is_dragging
  7098. else:
  7099. event_pos = (event.xdata, event.ydata)
  7100. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7101. if self.defaults["global_pan_button"] == '2':
  7102. pan_button = 3
  7103. else:
  7104. pan_button = 2
  7105. self.event_is_dragging = self.plotcanvas.is_dragging
  7106. # So it can receive key presses
  7107. self.plotcanvas.native.setFocus()
  7108. self.pos_jump = event_pos
  7109. self.ui.popMenu.mouse_is_panning = False
  7110. if not origin_click:
  7111. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7112. if event.button == pan_button and self.event_is_dragging == 1:
  7113. self.ui.popMenu.mouse_is_panning = True
  7114. return
  7115. if self.rel_point1 is not None:
  7116. try: # May fail in case mouse not within axes
  7117. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7118. if self.grid_status() == True:
  7119. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7120. # Update cursor
  7121. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7122. symbol='++', edge_color=self.cursor_color_3D,
  7123. size=self.defaults["global_cursor_size"])
  7124. else:
  7125. pos = (pos_canvas[0], pos_canvas[1])
  7126. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7127. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7128. dx = pos[0] - float(self.rel_point1[0])
  7129. dy = pos[1] - float(self.rel_point1[1])
  7130. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7131. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7132. self.mouse = [pos[0], pos[1]]
  7133. # if the mouse is moved and the LMB is clicked then the action is a selection
  7134. if self.event_is_dragging == 1 and event.button == 1:
  7135. self.delete_selection_shape()
  7136. if dx < 0:
  7137. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7138. face_color=self.defaults['global_alt_sel_fill'])
  7139. self.selection_type = False
  7140. elif dx > 0:
  7141. self.draw_moving_selection_shape(self.pos, pos)
  7142. self.selection_type = True
  7143. else:
  7144. self.selection_type = None
  7145. # hover effect - enabled in Preferences -> General -> GUI Settings
  7146. if self.defaults['global_hover']:
  7147. for obj in self.collection.get_list():
  7148. try:
  7149. # select the object(s) only if it is enabled (plotted)
  7150. if obj.options['plot']:
  7151. if obj not in self.collection.get_selected():
  7152. poly_obj = Polygon(
  7153. [(obj.options['xmin'], obj.options['ymin']),
  7154. (obj.options['xmax'], obj.options['ymin']),
  7155. (obj.options['xmax'], obj.options['ymax']),
  7156. (obj.options['xmin'], obj.options['ymax'])]
  7157. )
  7158. if Point(pos).within(poly_obj):
  7159. if obj.isHovering is False:
  7160. obj.isHovering = True
  7161. obj.notHovering = True
  7162. # create the selection box around the selected object
  7163. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7164. else:
  7165. if obj.notHovering is True:
  7166. obj.notHovering = False
  7167. obj.isHovering = False
  7168. self.delete_hover_shape()
  7169. except Exception:
  7170. # the Exception here will happen if we try to select on screen and we have an
  7171. # newly (and empty) just created Geometry or Excellon object that do not have the
  7172. # xmin, xmax, ymin, ymax options.
  7173. # In this case poly_obj creation (see above) will fail
  7174. pass
  7175. except Exception:
  7176. self.ui.position_label.setText("")
  7177. self.ui.rel_position_label.setText("")
  7178. self.mouse = None
  7179. def on_mouse_click_release_over_plot(self, event):
  7180. """
  7181. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7182. and has been registered in ''self.__init__()''.
  7183. :param event: contains information about the event.
  7184. :return:
  7185. """
  7186. if self.is_legacy is False:
  7187. event_pos = event.pos
  7188. right_button = 2
  7189. else:
  7190. event_pos = (event.xdata, event.ydata)
  7191. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7192. right_button = 3
  7193. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7194. if self.grid_status() == True:
  7195. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7196. else:
  7197. pos = (pos_canvas[0], pos_canvas[1])
  7198. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7199. # canvas menu
  7200. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7201. self.cursor = QtGui.QCursor()
  7202. self.populate_cmenu_grids()
  7203. self.ui.popMenu.popup(self.cursor.pos())
  7204. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7205. # selection and then select a type of selection ("enclosing" or "touching")
  7206. if event.button == 1: # left click
  7207. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7208. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7209. if modifiers == QtCore.Qt.ShiftModifier:
  7210. # do not auto open the Project Tab
  7211. self.click_noproject = True
  7212. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7213. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7214. return
  7215. if self.doubleclick is True:
  7216. self.doubleclick = False
  7217. if self.collection.get_selected():
  7218. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7219. if self.ui.splitter.sizes()[0] == 0:
  7220. self.ui.splitter.setSizes([1, 1])
  7221. try:
  7222. # delete the selection shape(S) as it may be in the way
  7223. self.delete_selection_shape()
  7224. self.delete_hover_shape()
  7225. except Exception as e:
  7226. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7227. return
  7228. else:
  7229. if self.selection_type is not None:
  7230. try:
  7231. self.selection_area_handler(self.pos, pos, self.selection_type)
  7232. self.selection_type = None
  7233. except Exception as e:
  7234. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7235. return
  7236. else:
  7237. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7238. if key_modifier == QtCore.Qt.ShiftModifier:
  7239. mod_key = 'Shift'
  7240. elif key_modifier == QtCore.Qt.ControlModifier:
  7241. mod_key = 'Control'
  7242. else:
  7243. mod_key = None
  7244. try:
  7245. if mod_key == self.defaults["global_mselect_key"]:
  7246. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7247. # deselect, and if it's not selected then it will be selected
  7248. # If there is no active command (self.command_active is None) then we check if we clicked
  7249. # on a object by checking the bounding limits against mouse click position
  7250. if self.command_active is None:
  7251. self.select_objects(key='CTRL')
  7252. self.delete_hover_shape()
  7253. else:
  7254. # If there is no active command (self.command_active is None) then we check if we clicked
  7255. # on a object by checking the bounding limits against mouse click position
  7256. if self.command_active is None:
  7257. self.select_objects()
  7258. self.delete_hover_shape()
  7259. except Exception as e:
  7260. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7261. return
  7262. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7263. """
  7264. :param start_pos: mouse position when the selection LMB click was done
  7265. :param end_pos: mouse position when the left mouse button is released
  7266. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7267. :return:
  7268. """
  7269. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7270. # delete previous selection shape
  7271. self.delete_selection_shape()
  7272. # make all objects inactive
  7273. self.collection.set_all_inactive()
  7274. for obj in self.collection.get_list():
  7275. try:
  7276. # select the object(s) only if it is enabled (plotted)
  7277. if obj.options['plot']:
  7278. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7279. (obj.options['xmax'], obj.options['ymin']),
  7280. (obj.options['xmax'], obj.options['ymax']),
  7281. (obj.options['xmin'], obj.options['ymax'])])
  7282. if sel_type is True:
  7283. if poly_obj.within(poly_selection):
  7284. # create the selection box around the selected object
  7285. if self.defaults['global_selection_shape'] is True:
  7286. self.draw_selection_shape(obj)
  7287. self.collection.set_active(obj.options['name'])
  7288. else:
  7289. if poly_selection.intersects(poly_obj):
  7290. # create the selection box around the selected object
  7291. if self.defaults['global_selection_shape'] is True:
  7292. self.draw_selection_shape(obj)
  7293. self.collection.set_active(obj.options['name'])
  7294. except Exception as e:
  7295. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7296. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7297. # In this case poly_obj creation (see above) will fail
  7298. log.debug("App.selection_area_handler() --> %s" % str(e))
  7299. def select_objects(self, key=None):
  7300. """
  7301. Will select objects clicked on canvas
  7302. :param key: for future use in cumulative selection
  7303. :return:
  7304. """
  7305. # list where we store the overlapped objects under our mouse left click position
  7306. objects_under_the_click_list = []
  7307. # Populate the list with the overlapped objects on the click position
  7308. curr_x, curr_y = self.pos
  7309. for obj in self.all_objects_list:
  7310. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7311. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7312. continue
  7313. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7314. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7315. if obj.options['name'] not in objects_under_the_click_list:
  7316. if obj.options['plot']:
  7317. # add objects to the objects_under_the_click list only if the object is plotted
  7318. # (active and not disabled)
  7319. objects_under_the_click_list.append(obj.options['name'])
  7320. try:
  7321. if objects_under_the_click_list:
  7322. curr_sel_obj = self.collection.get_active()
  7323. # case when there is only an object under the click and we toggle it
  7324. if len(objects_under_the_click_list) == 1:
  7325. if curr_sel_obj is None:
  7326. self.collection.set_active(objects_under_the_click_list[0])
  7327. curr_sel_obj = self.collection.get_active()
  7328. # create the selection box around the selected object
  7329. if self.defaults['global_selection_shape'] is True:
  7330. self.draw_selection_shape(curr_sel_obj)
  7331. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7332. self.on_objects_selection(False)
  7333. self.delete_selection_shape()
  7334. self.collection.set_active(objects_under_the_click_list[0])
  7335. curr_sel_obj = self.collection.get_active()
  7336. # create the selection box around the selected object
  7337. if self.defaults['global_selection_shape'] is True:
  7338. self.draw_selection_shape(curr_sel_obj)
  7339. self.selected_message(curr_sel_obj=curr_sel_obj)
  7340. else:
  7341. self.on_objects_selection(False)
  7342. self.delete_selection_shape()
  7343. if self.call_source != 'app':
  7344. self.call_source = 'app'
  7345. self.selected_message(curr_sel_obj=curr_sel_obj)
  7346. else:
  7347. # If there is no selected object
  7348. # make active the first element of the overlapped objects list
  7349. if self.collection.get_active() is None:
  7350. self.collection.set_active(objects_under_the_click_list[0])
  7351. name_sel_obj = self.collection.get_active().options['name']
  7352. # In case that there is a selected object but it is not in the overlapped object list
  7353. # make that object inactive and activate the first element in the overlapped object list
  7354. if name_sel_obj not in objects_under_the_click_list:
  7355. self.collection.set_inactive(name_sel_obj)
  7356. name_sel_obj = objects_under_the_click_list[0]
  7357. self.collection.set_active(name_sel_obj)
  7358. else:
  7359. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7360. self.collection.set_all_inactive()
  7361. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7362. len(objects_under_the_click_list)])
  7363. curr_sel_obj = self.collection.get_active()
  7364. # delete the possible selection box around a possible selected object
  7365. self.delete_selection_shape()
  7366. # create the selection box around the selected object
  7367. if self.defaults['global_selection_shape'] is True:
  7368. self.draw_selection_shape(curr_sel_obj)
  7369. self.selected_message(curr_sel_obj=curr_sel_obj)
  7370. else:
  7371. # deselect everything
  7372. self.on_objects_selection(False)
  7373. # delete the possible selection box around a possible selected object
  7374. self.delete_selection_shape()
  7375. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7376. # only when working on App
  7377. if self.call_source == 'app':
  7378. if self.click_noproject is False:
  7379. # if the Tool Tab is in focus don't change focus to Project Tab
  7380. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7381. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7382. else:
  7383. # restore auto open the Project Tab
  7384. self.click_noproject = False
  7385. # delete any text in the status bar, implicitly the last object name that was selected
  7386. # self.inform.emit("")
  7387. else:
  7388. self.call_source = 'app'
  7389. except Exception as e:
  7390. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7391. def selected_message(self, curr_sel_obj):
  7392. if curr_sel_obj:
  7393. if curr_sel_obj.kind == 'gerber':
  7394. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7395. color='green', name=str(curr_sel_obj.options['name'])))
  7396. elif curr_sel_obj.kind == 'excellon':
  7397. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7398. color='brown', name=str(curr_sel_obj.options['name'])))
  7399. elif curr_sel_obj.kind == 'cncjob':
  7400. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7401. color='blue', name=str(curr_sel_obj.options['name'])))
  7402. elif curr_sel_obj.kind == 'geometry':
  7403. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7404. color='red', name=str(curr_sel_obj.options['name'])))
  7405. def delete_hover_shape(self):
  7406. self.hover_shapes.clear()
  7407. self.hover_shapes.redraw()
  7408. def draw_hover_shape(self, sel_obj, color=None):
  7409. """
  7410. :param sel_obj: the object for which the hover shape must be drawn
  7411. :return:
  7412. """
  7413. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7414. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7415. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7416. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7417. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7418. if self.defaults['units'].upper() == 'MM':
  7419. hover_rect = hover_rect.buffer(-0.1)
  7420. hover_rect = hover_rect.buffer(0.2)
  7421. else:
  7422. hover_rect = hover_rect.buffer(-0.00393)
  7423. hover_rect = hover_rect.buffer(0.00787)
  7424. # if color:
  7425. # face = Color(color)
  7426. # face.alpha = 0.2
  7427. # outline = Color(color, alpha=0.8)
  7428. # else:
  7429. # face = Color(self.defaults['global_sel_fill'])
  7430. # face.alpha = 0.2
  7431. # outline = self.defaults['global_sel_line']
  7432. if color:
  7433. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7434. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7435. else:
  7436. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7437. outline = self.defaults['global_sel_line']
  7438. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7439. if self.is_legacy is True:
  7440. self.hover_shapes.redraw()
  7441. def delete_selection_shape(self):
  7442. self.move_tool.sel_shapes.clear()
  7443. self.move_tool.sel_shapes.redraw()
  7444. def draw_selection_shape(self, sel_obj, color=None):
  7445. """
  7446. :param sel_obj: the object for which the selection shape must be drawn
  7447. :return:
  7448. """
  7449. if sel_obj is None:
  7450. return
  7451. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7452. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7453. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7454. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7455. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7456. if self.defaults['units'].upper() == 'MM':
  7457. sel_rect = sel_rect.buffer(-0.1)
  7458. sel_rect = sel_rect.buffer(0.2)
  7459. else:
  7460. sel_rect = sel_rect.buffer(-0.00393)
  7461. sel_rect = sel_rect.buffer(0.00787)
  7462. if color:
  7463. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7464. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7465. else:
  7466. if self.is_legacy is False:
  7467. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7468. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7469. else:
  7470. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7471. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7472. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7473. color=outline,
  7474. face_color=face,
  7475. update=True,
  7476. layer=0,
  7477. tolerance=None))
  7478. if self.is_legacy is True:
  7479. self.move_tool.sel_shapes.redraw()
  7480. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7481. """
  7482. :param old_coords: old coordinates
  7483. :param coords: new coordinates
  7484. :return:
  7485. """
  7486. if 'color' in kwargs:
  7487. color = kwargs['color']
  7488. else:
  7489. color = self.defaults['global_sel_line']
  7490. if 'face_color' in kwargs:
  7491. face_color = kwargs['face_color']
  7492. else:
  7493. face_color = self.defaults['global_sel_fill']
  7494. if 'face_alpha' in kwargs:
  7495. face_alpha = kwargs['face_alpha']
  7496. else:
  7497. face_alpha = 0.3
  7498. x0, y0 = old_coords
  7499. x1, y1 = coords
  7500. pt1 = (x0, y0)
  7501. pt2 = (x1, y0)
  7502. pt3 = (x1, y1)
  7503. pt4 = (x0, y1)
  7504. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7505. # color_t = Color(face_color)
  7506. # color_t.alpha = face_alpha
  7507. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7508. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7509. layer=0, tolerance=None)
  7510. if self.is_legacy is True:
  7511. self.move_tool.sel_shapes.redraw()
  7512. def on_file_new_click(self):
  7513. if self.collection.get_list() and self.should_we_save:
  7514. msgbox = QtWidgets.QMessageBox()
  7515. # msgbox.setText("<B>Save changes ...</B>")
  7516. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7517. "Creating a New project will delete them.\n"
  7518. "Do you want to Save the project?"))
  7519. msgbox.setWindowTitle(_("Save changes"))
  7520. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7521. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7522. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7523. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7524. msgbox.setDefaultButton(bt_yes)
  7525. msgbox.exec_()
  7526. response = msgbox.clickedButton()
  7527. if response == bt_yes:
  7528. self.on_file_saveprojectas()
  7529. elif response == bt_cancel:
  7530. return
  7531. elif response == bt_no:
  7532. self.on_file_new()
  7533. else:
  7534. self.on_file_new()
  7535. self.inform.emit('[success] %s...' %
  7536. _("New Project created"))
  7537. def on_file_new(self, cli=None):
  7538. """
  7539. Callback for menu item File -> New. Returns the application to its
  7540. startup state. This method is thread-safe.
  7541. :return: None
  7542. """
  7543. self.report_usage("on_file_new")
  7544. # Remove everything from memory
  7545. App.log.debug("on_file_new()")
  7546. if self.call_source != 'app':
  7547. self.editor2object(cleanup=True)
  7548. # ## EDITOR section
  7549. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7550. self.exc_editor = FlatCAMExcEditor(self)
  7551. self.grb_editor = FlatCAMGrbEditor(self)
  7552. # Clear pool
  7553. self.clear_pool()
  7554. for obj in self.collection.get_list():
  7555. # delete shapes left drawn from mark shape_collections, if any
  7556. if isinstance(obj, FlatCAMGerber):
  7557. try:
  7558. obj.mark_shapes.enabled = False
  7559. obj.mark_shapes.clear(update=True)
  7560. except AttributeError:
  7561. pass
  7562. # also delete annotation shapes, if any
  7563. elif isinstance(obj, FlatCAMCNCjob):
  7564. try:
  7565. obj.annotation.enabled = False
  7566. obj.annotation.clear(update=True)
  7567. except AttributeError:
  7568. pass
  7569. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7570. self.init_tcl()
  7571. self.delete_selection_shape()
  7572. self.collection.delete_all()
  7573. self.setup_component_editor()
  7574. # Clear project filename
  7575. self.project_filename = None
  7576. # Load the application defaults
  7577. self.load_defaults(filename='current_defaults')
  7578. # Re-fresh project options
  7579. self.on_options_app2project()
  7580. # Init Tools
  7581. self.init_tools()
  7582. if cli is None:
  7583. # Close any Tabs opened in the Plot Tab Area section
  7584. for index in range(self.ui.plot_tab_area.count()):
  7585. self.ui.plot_tab_area.closeTab(index)
  7586. # for whatever reason previous command does not close the last tab so I do it manually
  7587. self.ui.plot_tab_area.closeTab(0)
  7588. # # And then add again the Plot Area
  7589. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7590. self.ui.plot_tab_area.protectTab(0)
  7591. # take the focus of the Notebook on Project Tab.
  7592. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7593. self.set_ui_title(name=_("New Project - Not saved"))
  7594. def obj_properties(self):
  7595. """
  7596. Will launch the object Properties Tool
  7597. :return:
  7598. """
  7599. self.report_usage("obj_properties()")
  7600. self.properties_tool.run(toggle=False)
  7601. def on_project_context_save(self):
  7602. """
  7603. Wrapper, will save the object function of it's type
  7604. :return:
  7605. """
  7606. obj = self.collection.get_active()
  7607. if type(obj) == FlatCAMGeometry:
  7608. self.on_file_exportdxf()
  7609. elif type(obj) == FlatCAMExcellon:
  7610. self.on_file_saveexcellon()
  7611. elif type(obj) == FlatCAMCNCjob:
  7612. obj.on_exportgcode_button_click()
  7613. elif type(obj) == FlatCAMGerber:
  7614. self.on_file_savegerber()
  7615. elif type(obj) == FlatCAMScript:
  7616. self.on_file_savescript()
  7617. elif type(obj) == FlatCAMDocument:
  7618. self.on_file_savedocument()
  7619. def obj_move(self):
  7620. self.report_usage("obj_move()")
  7621. self.move_tool.run(toggle=False)
  7622. def on_fileopengerber(self, signal: bool = None, name=None):
  7623. """
  7624. File menu callback for opening a Gerber.
  7625. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7626. :return: None
  7627. """
  7628. self.report_usage("on_fileopengerber")
  7629. App.log.debug("on_fileopengerber()")
  7630. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7631. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7632. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7633. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7634. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7635. "*.mil);;" \
  7636. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7637. "Allegro Files (*.art);;" \
  7638. "Mentor Files (*.pho *.gdo);;" \
  7639. "All Files (*.*)"
  7640. if name is None:
  7641. try:
  7642. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7643. directory=self.get_last_folder(),
  7644. filter=_filter_)
  7645. except TypeError:
  7646. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7647. filenames = [str(filename) for filename in filenames]
  7648. else:
  7649. filenames = [name]
  7650. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7651. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7652. _("Opening Gerber file.")),
  7653. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7654. color=QtGui.QColor("gray"))
  7655. if len(filenames) == 0:
  7656. self.inform.emit('[WARNING_NOTCL] %s' %
  7657. _("Open Gerber cancelled."))
  7658. else:
  7659. for filename in filenames:
  7660. if filename != '':
  7661. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7662. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7663. """
  7664. File menu callback for opening an Excellon file.
  7665. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7666. :return: None
  7667. """
  7668. self.report_usage("on_fileopenexcellon")
  7669. App.log.debug("on_fileopenexcellon()")
  7670. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7671. "All Files (*.*)"
  7672. if name is None:
  7673. try:
  7674. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7675. directory=self.get_last_folder(),
  7676. filter=_filter_)
  7677. except TypeError:
  7678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7679. filenames = [str(filename) for filename in filenames]
  7680. else:
  7681. filenames = [str(name)]
  7682. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7683. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7684. _("Opening Excellon file.")),
  7685. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7686. color=QtGui.QColor("gray"))
  7687. if len(filenames) == 0:
  7688. self.inform.emit('[WARNING_NOTCL]%s' %
  7689. _(" Open Excellon cancelled."))
  7690. else:
  7691. for filename in filenames:
  7692. if filename != '':
  7693. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7694. def on_fileopengcode(self, signal: bool = None, name=None):
  7695. """
  7696. File menu call back for opening gcode.
  7697. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7698. :return: None
  7699. """
  7700. self.report_usage("on_fileopengcode")
  7701. App.log.debug("on_fileopengcode()")
  7702. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7703. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7704. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7705. "All Files (*.*)"
  7706. if name is None:
  7707. try:
  7708. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7709. directory=self.get_last_folder(),
  7710. filter=_filter_)
  7711. except TypeError:
  7712. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7713. filenames = [str(filename) for filename in filenames]
  7714. else:
  7715. filenames = [name]
  7716. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7717. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7718. _("Opening G-Code file.")),
  7719. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7720. color=QtGui.QColor("gray"))
  7721. if len(filenames) == 0:
  7722. self.inform.emit('[WARNING_NOTCL] %s' %
  7723. _("Open G-Code cancelled."))
  7724. else:
  7725. for filename in filenames:
  7726. if filename != '':
  7727. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7728. def on_file_openproject(self, signal: bool = None):
  7729. """
  7730. File menu callback for opening a project.
  7731. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7732. :return: None
  7733. """
  7734. self.report_usage("on_file_openproject")
  7735. App.log.debug("on_file_openproject()")
  7736. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7737. try:
  7738. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7739. directory=self.get_last_folder(), filter=_filter_)
  7740. except TypeError:
  7741. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7742. # The Qt methods above will return a QString which can cause problems later.
  7743. # So far json.dump() will fail to serialize it.
  7744. # TODO: Improve the serialization methods and remove this fix.
  7745. filename = str(filename)
  7746. if filename == "":
  7747. self.inform.emit('[WARNING_NOTCL] %s' %
  7748. _("Open Project cancelled."))
  7749. else:
  7750. # self.worker_task.emit({'fcn': self.open_project,
  7751. # 'params': [filename]})
  7752. # The above was failing because open_project() is not
  7753. # thread safe. The new_project()
  7754. self.open_project(filename)
  7755. def on_file_openconfig(self, signal: bool = None):
  7756. """
  7757. File menu callback for opening a config file.
  7758. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7759. :return: None
  7760. """
  7761. self.report_usage("on_file_openconfig")
  7762. App.log.debug("on_file_openconfig()")
  7763. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7764. try:
  7765. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7766. directory=self.data_path, filter=_filter_)
  7767. except TypeError:
  7768. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7769. filter=_filter_)
  7770. if filename == "":
  7771. self.inform.emit('[WARNING_NOTCL] %s' %
  7772. _("Open Config cancelled."))
  7773. else:
  7774. self.open_config_file(filename)
  7775. def on_file_exportsvg(self):
  7776. """
  7777. Callback for menu item File->Export SVG.
  7778. :return: None
  7779. """
  7780. self.report_usage("on_file_exportsvg")
  7781. App.log.debug("on_file_exportsvg()")
  7782. obj = self.collection.get_active()
  7783. if obj is None:
  7784. self.inform.emit('[WARNING_NOTCL] %s' %
  7785. _("No object selected."))
  7786. msg = _("Please Select a Geometry object to export")
  7787. msgbox = QtWidgets.QMessageBox()
  7788. msgbox.setInformativeText(msg)
  7789. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7790. msgbox.setDefaultButton(bt_ok)
  7791. msgbox.exec_()
  7792. return
  7793. # Check for more compatible types and add as required
  7794. if (not isinstance(obj, FlatCAMGeometry)
  7795. and not isinstance(obj, FlatCAMGerber)
  7796. and not isinstance(obj, FlatCAMCNCjob)
  7797. and not isinstance(obj, FlatCAMExcellon)):
  7798. msg = '[ERROR_NOTCL] %s' % \
  7799. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7800. msgbox = QtWidgets.QMessageBox()
  7801. msgbox.setInformativeText(msg)
  7802. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7803. msgbox.setDefaultButton(bt_ok)
  7804. msgbox.exec_()
  7805. return
  7806. name = obj.options["name"]
  7807. _filter = "SVG File (*.svg);;All Files (*.*)"
  7808. try:
  7809. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7810. caption=_("Export SVG"),
  7811. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7812. filter=_filter)
  7813. except TypeError:
  7814. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7815. filename = str(filename)
  7816. if filename == "":
  7817. self.inform.emit('[WARNING_NOTCL]%s' %
  7818. _(" Export SVG cancelled."))
  7819. return
  7820. else:
  7821. self.export_svg(name, filename)
  7822. if self.defaults["global_open_style"] is False:
  7823. self.file_opened.emit("SVG", filename)
  7824. self.file_saved.emit("SVG", filename)
  7825. def on_file_exportpng(self):
  7826. self.report_usage("on_file_exportpng")
  7827. App.log.debug("on_file_exportpng()")
  7828. self.date = str(datetime.today()).rpartition('.')[0]
  7829. self.date = ''.join(c for c in self.date if c not in ':-')
  7830. self.date = self.date.replace(' ', '_')
  7831. if self.is_legacy is False:
  7832. image = _screenshot()
  7833. data = np.asarray(image)
  7834. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7835. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7836. _('Data must be a 3D array with last dimension 3 or 4'))
  7837. return
  7838. filter_ = "PNG File (*.png);;All Files (*.*)"
  7839. try:
  7840. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7841. caption=_("Export PNG Image"),
  7842. directory=self.get_last_save_folder() + '/png_' + self.date,
  7843. filter=filter_)
  7844. except TypeError:
  7845. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7846. filename = str(filename)
  7847. if filename == "":
  7848. self.inform.emit(_("Export PNG cancelled."))
  7849. return
  7850. else:
  7851. if self.is_legacy is False:
  7852. write_png(filename, data)
  7853. else:
  7854. self.plotcanvas.figure.savefig(filename)
  7855. if self.defaults["global_open_style"] is False:
  7856. self.file_opened.emit("png", filename)
  7857. self.file_saved.emit("png", filename)
  7858. def on_file_savegerber(self):
  7859. """
  7860. Callback for menu item in Project context menu.
  7861. :return: None
  7862. """
  7863. self.report_usage("on_file_savegerber")
  7864. App.log.debug("on_file_savegerber()")
  7865. obj = self.collection.get_active()
  7866. if obj is None:
  7867. self.inform.emit('[WARNING_NOTCL] %s' %
  7868. _("No object selected. Please select an Gerber object to export."))
  7869. return
  7870. # Check for more compatible types and add as required
  7871. if not isinstance(obj, FlatCAMGerber):
  7872. self.inform.emit('[ERROR_NOTCL] %s' %
  7873. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7874. return
  7875. name = self.collection.get_active().options["name"]
  7876. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7877. try:
  7878. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7879. caption="Save Gerber source file",
  7880. directory=self.get_last_save_folder() + '/' + name,
  7881. filter=_filter)
  7882. except TypeError:
  7883. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7884. filename = str(filename)
  7885. if filename == "":
  7886. self.inform.emit('[WARNING_NOTCL] %s' %
  7887. _("Save Gerber source file cancelled."))
  7888. return
  7889. else:
  7890. self.save_source_file(name, filename)
  7891. if self.defaults["global_open_style"] is False:
  7892. self.file_opened.emit("Gerber", filename)
  7893. self.file_saved.emit("Gerber", filename)
  7894. def on_file_savescript(self):
  7895. """
  7896. Callback for menu item in Project context menu.
  7897. :return: None
  7898. """
  7899. self.report_usage("on_file_savescript")
  7900. App.log.debug("on_file_savescript()")
  7901. obj = self.collection.get_active()
  7902. if obj is None:
  7903. self.inform.emit('[WARNING_NOTCL] %s' %
  7904. _("No object selected. Please select an Script object to export."))
  7905. return
  7906. # Check for more compatible types and add as required
  7907. if not isinstance(obj, FlatCAMScript):
  7908. self.inform.emit('[ERROR_NOTCL] %s' %
  7909. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7910. return
  7911. name = self.collection.get_active().options["name"]
  7912. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7913. try:
  7914. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7915. caption="Save Script source file",
  7916. directory=self.get_last_save_folder() + '/' + name,
  7917. filter=_filter)
  7918. except TypeError:
  7919. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7920. filename = str(filename)
  7921. if filename == "":
  7922. self.inform.emit('[WARNING_NOTCL] %s' %
  7923. _("Save Script source file cancelled."))
  7924. return
  7925. else:
  7926. self.save_source_file(name, filename)
  7927. if self.defaults["global_open_style"] is False:
  7928. self.file_opened.emit("Script", filename)
  7929. self.file_saved.emit("Script", filename)
  7930. def on_file_savedocument(self):
  7931. """
  7932. Callback for menu item in Project context menu.
  7933. :return: None
  7934. """
  7935. self.report_usage("on_file_savedocument")
  7936. App.log.debug("on_file_savedocument()")
  7937. obj = self.collection.get_active()
  7938. if obj is None:
  7939. self.inform.emit('[WARNING_NOTCL] %s' %
  7940. _("No object selected. Please select an Document object to export."))
  7941. return
  7942. # Check for more compatible types and add as required
  7943. if not isinstance(obj, FlatCAMScript):
  7944. self.inform.emit('[ERROR_NOTCL] %s' %
  7945. _("Failed. Only Document objects can be saved as Document files..."))
  7946. return
  7947. name = self.collection.get_active().options["name"]
  7948. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7949. try:
  7950. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7951. caption="Save Document source file",
  7952. directory=self.get_last_save_folder() + '/' + name,
  7953. filter=_filter)
  7954. except TypeError:
  7955. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7956. filename = str(filename)
  7957. if filename == "":
  7958. self.inform.emit('[WARNING_NOTCL] %s' %
  7959. _("Save Document source file cancelled."))
  7960. return
  7961. else:
  7962. self.save_source_file(name, filename)
  7963. if self.defaults["global_open_style"] is False:
  7964. self.file_opened.emit("Document", filename)
  7965. self.file_saved.emit("Document", filename)
  7966. def on_file_saveexcellon(self):
  7967. """
  7968. Callback for menu item in project context menu.
  7969. :return: None
  7970. """
  7971. self.report_usage("on_file_saveexcellon")
  7972. App.log.debug("on_file_saveexcellon()")
  7973. obj = self.collection.get_active()
  7974. if obj is None:
  7975. self.inform.emit('[WARNING_NOTCL] %s' %
  7976. _("No object selected. Please select an Excellon object to export."))
  7977. return
  7978. # Check for more compatible types and add as required
  7979. if not isinstance(obj, FlatCAMExcellon):
  7980. self.inform.emit('[ERROR_NOTCL] %s' %
  7981. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7982. return
  7983. name = self.collection.get_active().options["name"]
  7984. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7985. try:
  7986. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7987. caption=_("Save Excellon source file"),
  7988. directory=self.get_last_save_folder() + '/' + name,
  7989. filter=_filter)
  7990. except TypeError:
  7991. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7992. filename = str(filename)
  7993. if filename == "":
  7994. self.inform.emit('[WARNING_NOTCL] %s' %
  7995. _("Saving Excellon source file cancelled."))
  7996. return
  7997. else:
  7998. self.save_source_file(name, filename)
  7999. if self.defaults["global_open_style"] is False:
  8000. self.file_opened.emit("Excellon", filename)
  8001. self.file_saved.emit("Excellon", filename)
  8002. def on_file_exportexcellon(self):
  8003. """
  8004. Callback for menu item File->Export->Excellon.
  8005. :return: None
  8006. """
  8007. self.report_usage("on_file_exportexcellon")
  8008. App.log.debug("on_file_exportexcellon()")
  8009. obj = self.collection.get_active()
  8010. if obj is None:
  8011. self.inform.emit('[WARNING_NOTCL] %s' %
  8012. _("No object selected. Please Select an Excellon object to export."))
  8013. return
  8014. # Check for more compatible types and add as required
  8015. if not isinstance(obj, FlatCAMExcellon):
  8016. self.inform.emit('[ERROR_NOTCL] %s' %
  8017. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8018. return
  8019. name = self.collection.get_active().options["name"]
  8020. _filter = self.defaults["excellon_save_filters"]
  8021. try:
  8022. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8023. caption=_("Export Excellon"),
  8024. directory=self.get_last_save_folder() + '/' + name,
  8025. filter=_filter)
  8026. except TypeError:
  8027. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8028. filename = str(filename)
  8029. if filename == "":
  8030. self.inform.emit('[WARNING_NOTCL] %s' %
  8031. _("Export Excellon cancelled."))
  8032. return
  8033. else:
  8034. used_extension = filename.rpartition('.')[2]
  8035. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8036. self.export_excellon(name, filename)
  8037. if self.defaults["global_open_style"] is False:
  8038. self.file_opened.emit("Excellon", filename)
  8039. self.file_saved.emit("Excellon", filename)
  8040. def on_file_exportgerber(self):
  8041. """
  8042. Callback for menu item File->Export->Gerber.
  8043. :return: None
  8044. """
  8045. self.report_usage("on_file_exportgerber")
  8046. App.log.debug("on_file_exportgerber()")
  8047. obj = self.collection.get_active()
  8048. if obj is None:
  8049. self.inform.emit('[WARNING_NOTCL] %s' %
  8050. _("No object selected. Please Select an Gerber object to export."))
  8051. return
  8052. # Check for more compatible types and add as required
  8053. if not isinstance(obj, FlatCAMGerber):
  8054. self.inform.emit('[ERROR_NOTCL] %s' %
  8055. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8056. return
  8057. name = self.collection.get_active().options["name"]
  8058. _filter_ = self.defaults['gerber_save_filters']
  8059. try:
  8060. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8061. caption=_("Export Gerber"),
  8062. directory=self.get_last_save_folder() + '/' + name,
  8063. filter=_filter_)
  8064. except TypeError:
  8065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8066. filename = str(filename)
  8067. if filename == "":
  8068. self.inform.emit('[WARNING_NOTCL] %s' %
  8069. _("Export Gerber cancelled."))
  8070. return
  8071. else:
  8072. used_extension = filename.rpartition('.')[2]
  8073. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8074. self.export_gerber(name, filename)
  8075. if self.defaults["global_open_style"] is False:
  8076. self.file_opened.emit("Gerber", filename)
  8077. self.file_saved.emit("Gerber", filename)
  8078. def on_file_exportdxf(self):
  8079. """
  8080. Callback for menu item File->Export DXF.
  8081. :return: None
  8082. """
  8083. self.report_usage("on_file_exportdxf")
  8084. App.log.debug("on_file_exportdxf()")
  8085. obj = self.collection.get_active()
  8086. if obj is None:
  8087. self.inform.emit('[WARNING_NOTCL] %s' %
  8088. _("No object selected."))
  8089. msg = _("Please Select a Geometry object to export")
  8090. msgbox = QtWidgets.QMessageBox()
  8091. msgbox.setInformativeText(msg)
  8092. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8093. msgbox.setDefaultButton(bt_ok)
  8094. msgbox.exec_()
  8095. return
  8096. # Check for more compatible types and add as required
  8097. if not isinstance(obj, FlatCAMGeometry):
  8098. msg = '[ERROR_NOTCL] %s' % \
  8099. _("Only Geometry objects can be used.")
  8100. msgbox = QtWidgets.QMessageBox()
  8101. msgbox.setInformativeText(msg)
  8102. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8103. msgbox.setDefaultButton(bt_ok)
  8104. msgbox.exec_()
  8105. return
  8106. name = self.collection.get_active().options["name"]
  8107. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8108. try:
  8109. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8110. caption=_("Export DXF"),
  8111. directory=self.get_last_save_folder() + '/' + name,
  8112. filter=_filter_)
  8113. except TypeError:
  8114. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8115. filter=_filter_)
  8116. filename = str(filename)
  8117. if filename == "":
  8118. self.inform.emit('[WARNING_NOTCL] %s' %
  8119. _("Export DXF cancelled."))
  8120. return
  8121. else:
  8122. self.export_dxf(name, filename)
  8123. if self.defaults["global_open_style"] is False:
  8124. self.file_opened.emit("DXF", filename)
  8125. self.file_saved.emit("DXF", filename)
  8126. def on_file_importsvg(self, type_of_obj):
  8127. """
  8128. Callback for menu item File->Import SVG.
  8129. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8130. :type type_of_obj: str
  8131. :return: None
  8132. """
  8133. self.report_usage("on_file_importsvg")
  8134. App.log.debug("on_file_importsvg()")
  8135. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8136. try:
  8137. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8138. directory=self.get_last_folder(), filter=_filter_)
  8139. except TypeError:
  8140. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8141. filter=_filter_)
  8142. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8143. type_of_obj = "geometry"
  8144. filenames = [str(filename) for filename in filenames]
  8145. if len(filenames) == 0:
  8146. self.inform.emit('[WARNING_NOTCL] %s' %
  8147. _("Open SVG cancelled."))
  8148. else:
  8149. for filename in filenames:
  8150. if filename != '':
  8151. self.worker_task.emit({'fcn': self.import_svg,
  8152. 'params': [filename, type_of_obj]})
  8153. def on_file_importdxf(self, type_of_obj):
  8154. """
  8155. Callback for menu item File->Import DXF.
  8156. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8157. :type type_of_obj: str
  8158. :return: None
  8159. """
  8160. self.report_usage("on_file_importdxf")
  8161. App.log.debug("on_file_importdxf()")
  8162. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8163. try:
  8164. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8165. directory=self.get_last_folder(),
  8166. filter=_filter_)
  8167. except TypeError:
  8168. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8169. filter=_filter_)
  8170. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8171. type_of_obj = "geometry"
  8172. filenames = [str(filename) for filename in filenames]
  8173. if len(filenames) == 0:
  8174. self.inform.emit('[WARNING_NOTCL] %s' %
  8175. _("Open DXF cancelled."))
  8176. else:
  8177. for filename in filenames:
  8178. if filename != '':
  8179. self.worker_task.emit({'fcn': self.import_dxf,
  8180. 'params': [filename, type_of_obj]})
  8181. # ###############################################################################################################
  8182. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8183. # ###############################################################################################################
  8184. def init_code_editor(self, name):
  8185. self.text_editor_tab = TextEditor(app=self)
  8186. # add the tab if it was closed
  8187. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8188. self.text_editor_tab.setObjectName('text_editor_tab')
  8189. # delete the absolute and relative position and messages in the infobar
  8190. self.ui.position_label.setText("")
  8191. self.ui.rel_position_label.setText("")
  8192. # first clear previous text in text editor (if any)
  8193. self.text_editor_tab.code_editor.clear()
  8194. self.text_editor_tab.code_editor.setReadOnly(False)
  8195. self.toggle_codeeditor = True
  8196. self.text_editor_tab.code_editor.completer_enable = False
  8197. self.text_editor_tab.buttonRun.hide()
  8198. # make sure to keep a reference to the code editor
  8199. self.reference_code_editor = self.text_editor_tab.code_editor
  8200. # Switch plot_area to CNCJob tab
  8201. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8202. def on_view_source(self):
  8203. """
  8204. Called when the user wants to see the source file of the selected object
  8205. :return:
  8206. """
  8207. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8208. self.proc_container.view.set_busy(_("Loading..."))
  8209. try:
  8210. obj = self.collection.get_active()
  8211. except Exception as e:
  8212. log.debug("App.on_view_source() --> %s" % str(e))
  8213. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8214. return 'fail'
  8215. if obj is None:
  8216. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8217. return 'fail'
  8218. flt = "All Files (*.*)"
  8219. if obj.kind == 'gerber':
  8220. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8221. elif obj.kind == 'excellon':
  8222. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8223. elif obj.kind == 'cncjob':
  8224. "GCode Files (*.NC);;All Files (*.*)"
  8225. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8226. # add the tab if it was closed
  8227. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8228. self.source_editor_tab.setObjectName('source_editor_tab')
  8229. # delete the absolute and relative position and messages in the infobar
  8230. self.ui.position_label.setText("")
  8231. self.ui.rel_position_label.setText("")
  8232. # first clear previous text in text editor (if any)
  8233. self.source_editor_tab.code_editor.clear()
  8234. self.source_editor_tab.code_editor.setReadOnly(False)
  8235. self.source_editor_tab.code_editor.completer_enable = False
  8236. self.source_editor_tab.buttonRun.hide()
  8237. # Switch plot_area to CNCJob tab
  8238. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8239. try:
  8240. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8241. except TypeError:
  8242. pass
  8243. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8244. try:
  8245. self.source_editor_tab.buttonSave.clicked.disconnect()
  8246. except TypeError:
  8247. pass
  8248. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8249. # then append the text from GCode to the text editor
  8250. if obj.kind == 'cncjob':
  8251. try:
  8252. file = obj.export_gcode(
  8253. preamble=self.defaults["cncjob_prepend"],
  8254. postamble=self.defaults["cncjob_append"],
  8255. to_file=True)
  8256. if file == 'fail':
  8257. return 'fail'
  8258. except AttributeError:
  8259. self.inform.emit('[WARNING_NOTCL] %s' %
  8260. _("There is no selected object for which to see it's source file code."))
  8261. return 'fail'
  8262. else:
  8263. try:
  8264. file = StringIO(obj.source_file)
  8265. except (AttributeError, TypeError):
  8266. self.inform.emit('[WARNING_NOTCL] %s' %
  8267. _("There is no selected object for which to see it's source file code."))
  8268. return 'fail'
  8269. self.source_editor_tab.t_frame.hide()
  8270. try:
  8271. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8272. # for line in file:
  8273. # QtWidgets.QApplication.processEvents()
  8274. # proc_line = str(line).strip('\n')
  8275. # self.source_editor_tab.code_editor.append(proc_line)
  8276. except Exception as e:
  8277. log.debug('App.on_view_source() -->%s' % str(e))
  8278. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8279. return
  8280. self.source_editor_tab.handleTextChanged()
  8281. self.source_editor_tab.t_frame.show()
  8282. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8283. self.proc_container.view.set_idle()
  8284. # self.ui.show()
  8285. def on_toggle_code_editor(self):
  8286. self.report_usage("on_toggle_code_editor()")
  8287. if self.toggle_codeeditor is False:
  8288. self.init_code_editor(name=_("Code Editor"))
  8289. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8290. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8291. self.text_editor_tab.buttonSave.clicked.disconnect()
  8292. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8293. else:
  8294. for idx in range(self.ui.plot_tab_area.count()):
  8295. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8296. self.ui.plot_tab_area.closeTab(idx)
  8297. break
  8298. self.toggle_codeeditor = False
  8299. def on_code_editor_close(self):
  8300. print("closed")
  8301. self.toggle_codeeditor = False
  8302. def on_filenewscript(self, silent=False, name=None, text=None):
  8303. """
  8304. Will create a new script file and open it in the Code Editor
  8305. :param silent: if True will not display status messages
  8306. :param name: if specified will be the name of the new script
  8307. :param text: pass a source file to the newly created script to be loaded in it
  8308. :return: None
  8309. """
  8310. if silent is False:
  8311. self.inform.emit('[success] %s' %
  8312. _("New TCL script file created in Code Editor."))
  8313. # delete the absolute and relative position and messages in the infobar
  8314. self.ui.position_label.setText("")
  8315. self.ui.rel_position_label.setText("")
  8316. if name is not None:
  8317. self.new_script_object(name=name, text=text)
  8318. else:
  8319. self.new_script_object(text=text)
  8320. # script_text = script_obj.source_file
  8321. #
  8322. # self.proc_container.view.set_busy(_("Loading..."))
  8323. # script_obj.script_editor_tab.t_frame.hide()
  8324. #
  8325. # script_obj.script_editor_tab.t_frame.show()
  8326. # self.proc_container.view.set_idle()
  8327. def on_fileopenscript(self, name=None, silent=False):
  8328. """
  8329. Will open a Tcl script file into the Code Editor
  8330. :param silent: if True will not display status messages
  8331. :param name: name of a Tcl script file to open
  8332. :return:
  8333. """
  8334. self.report_usage("on_fileopenscript")
  8335. App.log.debug("on_fileopenscript()")
  8336. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8337. if name:
  8338. filenames = [name]
  8339. else:
  8340. try:
  8341. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8342. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8343. except TypeError:
  8344. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8345. if len(filenames) == 0:
  8346. if silent is False:
  8347. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8348. else:
  8349. for filename in filenames:
  8350. if filename != '':
  8351. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8352. def on_filerunscript(self, name=None, silent=False):
  8353. """
  8354. File menu callback for loading and running a TCL script.
  8355. :param silent: if True will not display status messages
  8356. :param name: name of a Tcl script file to be run by FlatCAM
  8357. :return: None
  8358. """
  8359. self.report_usage("on_filerunscript")
  8360. App.log.debug("on_file_runscript()")
  8361. if name:
  8362. filename = name
  8363. if self.cmd_line_headless != 1:
  8364. self.splash.showMessage('%s: %ssec\n%s' %
  8365. (_("Canvas initialization started.\n"
  8366. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8367. _("Executing FlatCAMScript file.")
  8368. ),
  8369. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8370. color=QtGui.QColor("gray"))
  8371. else:
  8372. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8373. try:
  8374. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8375. directory=self.get_last_folder(), filter=_filter_)
  8376. except TypeError:
  8377. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8378. # The Qt methods above will return a QString which can cause problems later.
  8379. # So far json.dump() will fail to serialize it.
  8380. # TODO: Improve the serialization methods and remove this fix.
  8381. filename = str(filename)
  8382. if filename == "":
  8383. if silent is False:
  8384. self.inform.emit('[WARNING_NOTCL] %s' %
  8385. _("Run TCL script cancelled."))
  8386. else:
  8387. if self.cmd_line_headless != 1:
  8388. if self.ui.shell_dock.isHidden():
  8389. self.ui.shell_dock.show()
  8390. try:
  8391. with open(filename, "r") as tcl_script:
  8392. cmd_line_shellfile_content = tcl_script.read()
  8393. if self.cmd_line_headless != 1:
  8394. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8395. else:
  8396. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8397. if silent is False:
  8398. self.inform.emit('[success] %s' %
  8399. _("TCL script file opened in Code Editor and executed."))
  8400. except Exception as e:
  8401. log.debug("App.on_filerunscript() -> %s" % str(e))
  8402. sys.exit(2)
  8403. def on_file_saveproject(self, silent=False):
  8404. """
  8405. Callback for menu item File->Save Project. Saves the project to
  8406. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8407. if set to None. The project is saved by calling ``self.save_project()``.
  8408. :param silent: if True will not display status messages
  8409. :return: None
  8410. """
  8411. self.report_usage("on_file_saveproject")
  8412. if self.project_filename is None:
  8413. self.on_file_saveprojectas()
  8414. else:
  8415. self.worker_task.emit({'fcn': self.save_project,
  8416. 'params': [self.project_filename, silent]})
  8417. if self.defaults["global_open_style"] is False:
  8418. self.file_opened.emit("project", self.project_filename)
  8419. self.file_saved.emit("project", self.project_filename)
  8420. self.set_ui_title(name=self.project_filename)
  8421. self.should_we_save = False
  8422. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8423. """
  8424. Callback for menu item File->Save Project As... Opens a file
  8425. chooser and saves the project to the given file via
  8426. ``self.save_project()``.
  8427. :param make_copy if to be create a copy of the project; boolean
  8428. :param use_thread: if to be run in a separate thread; boolean
  8429. :param quit_action: if to be followed by quiting the application; boolean
  8430. :return: None
  8431. """
  8432. self.report_usage("on_file_saveprojectas")
  8433. self.date = str(datetime.today()).rpartition('.')[0]
  8434. self.date = ''.join(c for c in self.date if c not in ':-')
  8435. self.date = self.date.replace(' ', '_')
  8436. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8437. try:
  8438. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8439. caption=_("Save Project As ..."),
  8440. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8441. filter=filter_)
  8442. except TypeError:
  8443. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8444. filename = str(filename)
  8445. if filename == '':
  8446. self.inform.emit('[WARNING_NOTCL] %s' %
  8447. _("Save Project cancelled."))
  8448. return
  8449. try:
  8450. f = open(filename, 'r')
  8451. f.close()
  8452. except IOError:
  8453. pass
  8454. if use_thread is True:
  8455. self.worker_task.emit({'fcn': self.save_project,
  8456. 'params': [filename, quit_action]})
  8457. else:
  8458. self.save_project(filename, quit_action)
  8459. # self.save_project(filename)
  8460. if self.defaults["global_open_style"] is False:
  8461. self.file_opened.emit("project", filename)
  8462. self.file_saved.emit("project", filename)
  8463. if not make_copy:
  8464. self.project_filename = filename
  8465. self.set_ui_title(name=self.project_filename)
  8466. self.should_we_save = False
  8467. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8468. """
  8469. Exports a Geometry Object to an SVG file.
  8470. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8471. :param filename: Path to the SVG file to save to.
  8472. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8473. :return:
  8474. """
  8475. self.report_usage("export_svg()")
  8476. if filename is None:
  8477. filename = self.defaults["global_last_save_folder"]
  8478. self.log.debug("export_svg()")
  8479. try:
  8480. obj = self.collection.get_by_name(str(obj_name))
  8481. except Exception:
  8482. # TODO: The return behavior has not been established... should raise exception?
  8483. return "Could not retrieve object: %s" % obj_name
  8484. with self.proc_container.new(_("Exporting SVG")) as proc:
  8485. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8486. # Determine bounding area for svg export
  8487. bounds = obj.bounds()
  8488. size = obj.size()
  8489. # Convert everything to strings for use in the xml doc
  8490. svgwidth = str(size[0])
  8491. svgheight = str(size[1])
  8492. minx = str(bounds[0])
  8493. miny = str(bounds[1] - size[1])
  8494. uom = obj.units.lower()
  8495. # Add a SVG Header and footer to the svg output from shapely
  8496. # The transform flips the Y Axis so that everything renders
  8497. # properly within svg apps such as inkscape
  8498. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8499. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8500. svg_header += 'width="' + svgwidth + uom + '" '
  8501. svg_header += 'height="' + svgheight + uom + '" '
  8502. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8503. svg_header += '<g transform="scale(1,-1)">'
  8504. svg_footer = '</g> </svg>'
  8505. svg_elem = svg_header + exported_svg + svg_footer
  8506. # Parse the xml through a xml parser just to add line feeds
  8507. # and to make it look more pretty for the output
  8508. svgcode = parse_xml_string(svg_elem)
  8509. svgcode = svgcode.toprettyxml()
  8510. try:
  8511. with open(filename, 'w') as fp:
  8512. fp.write(svgcode)
  8513. except PermissionError:
  8514. self.inform.emit('[WARNING] %s' %
  8515. _("Permission denied, saving not possible.\n"
  8516. "Most likely another app is holding the file open and not accessible."))
  8517. return 'fail'
  8518. if self.defaults["global_open_style"] is False:
  8519. self.file_opened.emit("SVG", filename)
  8520. self.file_saved.emit("SVG", filename)
  8521. self.inform.emit('[success] %s: %s' %
  8522. (_("SVG file exported to"), filename))
  8523. def save_source_file(self, obj_name, filename, use_thread=True):
  8524. """
  8525. Exports a FlatCAM Object to an Gerber/Excellon file.
  8526. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8527. :param filename: Path to the Gerber file to save to.
  8528. :param use_thread: if to be run in a separate thread
  8529. :return:
  8530. """
  8531. self.report_usage("save source file()")
  8532. if filename is None:
  8533. filename = self.defaults["global_last_save_folder"]
  8534. self.log.debug("save source file()")
  8535. obj = self.collection.get_by_name(obj_name)
  8536. file_string = StringIO(obj.source_file)
  8537. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8538. if file_string.getvalue() == '':
  8539. self.inform.emit('[ERROR_NOTCL] %s' %
  8540. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8541. return 'fail'
  8542. try:
  8543. with open(filename, 'w') as file:
  8544. file.writelines('G04*\n')
  8545. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8546. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8547. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8548. file.writelines('G04 Created on : %s*\n' % time_string)
  8549. for line in file_string:
  8550. file.writelines(line)
  8551. except PermissionError:
  8552. self.inform.emit('[WARNING] %s' %
  8553. _("Permission denied, saving not possible.\n"
  8554. "Most likely another app is holding the file open and not accessible."))
  8555. return 'fail'
  8556. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8557. """
  8558. Exports a Excellon Object to an Excellon file.
  8559. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8560. :param filename: Path to the Excellon file to save to.
  8561. :param local_use:
  8562. :param use_thread: if to be run in a separate thread
  8563. :return:
  8564. """
  8565. self.report_usage("export_excellon()")
  8566. if filename is None:
  8567. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8568. self.log.debug("export_excellon()")
  8569. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8570. self.defaults["excellon_exp_decimals"]
  8571. )
  8572. if local_use is None:
  8573. try:
  8574. obj = self.collection.get_by_name(str(obj_name))
  8575. except Exception:
  8576. # TODO: The return behavior has not been established... should raise exception?
  8577. return "Could not retrieve object: %s" % obj_name
  8578. else:
  8579. obj = local_use
  8580. if not isinstance(obj, FlatCAMExcellon):
  8581. self.inform.emit('[ERROR_NOTCL] %s' %
  8582. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8583. return
  8584. # updated units
  8585. eunits = self.defaults["excellon_exp_units"]
  8586. ewhole = self.defaults["excellon_exp_integer"]
  8587. efract = self.defaults["excellon_exp_decimals"]
  8588. ezeros = self.defaults["excellon_exp_zeros"]
  8589. eformat = self.defaults["excellon_exp_format"]
  8590. slot_type = self.defaults["excellon_exp_slot_type"]
  8591. fc_units = self.defaults['units'].upper()
  8592. if fc_units == 'MM':
  8593. factor = 1 if eunits == 'METRIC' else 0.03937
  8594. else:
  8595. factor = 25.4 if eunits == 'METRIC' else 1
  8596. def make_excellon():
  8597. try:
  8598. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8599. header = 'M48\n'
  8600. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8601. (str(self.version), str(self.version_date))
  8602. header += ';Filename: %s' % str(obj_name) + '\n'
  8603. header += ';Created on : %s' % time_str + '\n'
  8604. if eformat == 'dec':
  8605. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8606. header += eunits + '\n'
  8607. for tool in obj.tools:
  8608. if eunits == 'METRIC':
  8609. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8610. tool=str(tool),
  8611. dec=2)
  8612. else:
  8613. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8614. tool=str(tool),
  8615. dec=4)
  8616. else:
  8617. if ezeros == 'LZ':
  8618. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8619. form='ndec', e_zeros='LZ', factor=factor,
  8620. slot_type=slot_type)
  8621. header += '%s,%s\n' % (eunits, 'LZ')
  8622. header += format_exc
  8623. for tool in obj.tools:
  8624. if eunits == 'METRIC':
  8625. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8626. tool=str(tool),
  8627. dec=2)
  8628. else:
  8629. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8630. tool=str(tool),
  8631. dec=4)
  8632. else:
  8633. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8634. form='ndec', e_zeros='TZ', factor=factor,
  8635. slot_type=slot_type)
  8636. header += '%s,%s\n' % (eunits, 'TZ')
  8637. header += format_exc
  8638. for tool in obj.tools:
  8639. if eunits == 'METRIC':
  8640. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8641. tool=str(tool),
  8642. dec=2)
  8643. else:
  8644. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8645. tool=str(tool),
  8646. dec=4)
  8647. header += '%\n'
  8648. footer = 'M30\n'
  8649. exported_excellon = header
  8650. exported_excellon += excellon_code
  8651. exported_excellon += footer
  8652. if local_use is None:
  8653. try:
  8654. with open(filename, 'w') as fp:
  8655. fp.write(exported_excellon)
  8656. except PermissionError:
  8657. self.inform.emit('[WARNING] %s' %
  8658. _("Permission denied, saving not possible.\n"
  8659. "Most likely another app is holding the file open and not accessible."))
  8660. return 'fail'
  8661. if self.defaults["global_open_style"] is False:
  8662. self.file_opened.emit("Excellon", filename)
  8663. self.file_saved.emit("Excellon", filename)
  8664. self.inform.emit('[success] %s: %s' %
  8665. (_("Excellon file exported to"), filename))
  8666. else:
  8667. return exported_excellon
  8668. except Exception as e:
  8669. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8670. return 'fail'
  8671. if use_thread is True:
  8672. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8673. def job_thread_exc(app_obj):
  8674. ret = make_excellon()
  8675. if ret == 'fail':
  8676. self.inform.emit('[ERROR_NOTCL] %s' %
  8677. _('Could not export Excellon file.'))
  8678. return
  8679. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8680. else:
  8681. ret = make_excellon()
  8682. if ret == 'fail':
  8683. self.inform.emit('[ERROR_NOTCL] %s' %
  8684. _('Could not export Excellon file.'))
  8685. return 'fail'
  8686. if local_use is not None:
  8687. return ret
  8688. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8689. """
  8690. Exports a Gerber Object to an Gerber file.
  8691. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8692. :param filename: Path to the Gerber file to save to.
  8693. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8694. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8695. :param use_thread: if to be run in a separate thread
  8696. :return:
  8697. """
  8698. self.report_usage("export_gerber()")
  8699. if filename is None:
  8700. filename = self.defaults["global_last_save_folder"]
  8701. self.log.debug("export_gerber()")
  8702. if local_use is None:
  8703. try:
  8704. obj = self.collection.get_by_name(str(obj_name))
  8705. except Exception:
  8706. # TODO: The return behavior has not been established... should raise exception?
  8707. return "Could not retrieve object: %s" % obj_name
  8708. else:
  8709. obj = local_use
  8710. # updated units
  8711. gunits = self.defaults["gerber_exp_units"]
  8712. gwhole = self.defaults["gerber_exp_integer"]
  8713. gfract = self.defaults["gerber_exp_decimals"]
  8714. gzeros = self.defaults["gerber_exp_zeros"]
  8715. fc_units = self.defaults['units'].upper()
  8716. if fc_units == 'MM':
  8717. factor = 1 if gunits == 'MM' else 0.03937
  8718. else:
  8719. factor = 25.4 if gunits == 'MM' else 1
  8720. def make_gerber():
  8721. try:
  8722. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8723. header = 'G04*\n'
  8724. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8725. (str(self.version), str(self.version_date))
  8726. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8727. header += 'G04 Created on : %s*' % time_str + '\n'
  8728. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8729. header += "%MO{units}*%\n".format(units=gunits)
  8730. for apid in obj.apertures:
  8731. if obj.apertures[apid]['type'] == 'C':
  8732. header += "%ADD{apid}{type},{size}*%\n".format(
  8733. apid=str(apid),
  8734. type='C',
  8735. size=(factor * obj.apertures[apid]['size'])
  8736. )
  8737. elif obj.apertures[apid]['type'] == 'R':
  8738. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8739. apid=str(apid),
  8740. type='R',
  8741. width=(factor * obj.apertures[apid]['width']),
  8742. height=(factor * obj.apertures[apid]['height'])
  8743. )
  8744. elif obj.apertures[apid]['type'] == 'O':
  8745. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8746. apid=str(apid),
  8747. type='O',
  8748. width=(factor * obj.apertures[apid]['width']),
  8749. height=(factor * obj.apertures[apid]['height'])
  8750. )
  8751. header += '\n'
  8752. # obsolete units but some software may need it
  8753. if gunits == 'IN':
  8754. header += 'G70*\n'
  8755. else:
  8756. header += 'G71*\n'
  8757. # Absolute Mode
  8758. header += 'G90*\n'
  8759. header += 'G01*\n'
  8760. # positive polarity
  8761. header += '%LPD*%\n'
  8762. footer = 'M02*\n'
  8763. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8764. exported_gerber = header
  8765. exported_gerber += gerber_code
  8766. exported_gerber += footer
  8767. if local_use is None:
  8768. try:
  8769. with open(filename, 'w') as fp:
  8770. fp.write(exported_gerber)
  8771. except PermissionError:
  8772. self.inform.emit('[WARNING] %s' %
  8773. _("Permission denied, saving not possible.\n"
  8774. "Most likely another app is holding the file open and not accessible."))
  8775. return 'fail'
  8776. if self.defaults["global_open_style"] is False:
  8777. self.file_opened.emit("Gerber", filename)
  8778. self.file_saved.emit("Gerber", filename)
  8779. self.inform.emit('[success] %s: %s' %
  8780. (_("Gerber file exported to"), filename))
  8781. else:
  8782. return exported_gerber
  8783. except Exception as e:
  8784. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8785. return 'fail'
  8786. if use_thread is True:
  8787. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8788. def job_thread_grb(app_obj):
  8789. ret = make_gerber()
  8790. if ret == 'fail':
  8791. self.inform.emit('[ERROR_NOTCL] %s' %
  8792. _('Could not export Gerber file.'))
  8793. return
  8794. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8795. else:
  8796. ret = make_gerber()
  8797. if ret == 'fail':
  8798. self.inform.emit('[ERROR_NOTCL] %s' %
  8799. _('Could not export Gerber file.'))
  8800. return 'fail'
  8801. if local_use is not None:
  8802. return ret
  8803. def export_dxf(self, obj_name, filename, use_thread=True):
  8804. """
  8805. Exports a Geometry Object to an DXF file.
  8806. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8807. :param filename: Path to the DXF file to save to.
  8808. :param use_thread: if to be run in a separate thread
  8809. :return:
  8810. """
  8811. self.report_usage("export_dxf()")
  8812. if filename is None:
  8813. filename = self.defaults["global_last_save_folder"]
  8814. self.log.debug("export_dxf()")
  8815. try:
  8816. obj = self.collection.get_by_name(str(obj_name))
  8817. except Exception:
  8818. # TODO: The return behavior has not been established... should raise exception?
  8819. return "Could not retrieve object: %s" % obj_name
  8820. def make_dxf():
  8821. try:
  8822. dxf_code = obj.export_dxf()
  8823. dxf_code.saveas(filename)
  8824. if self.defaults["global_open_style"] is False:
  8825. self.file_opened.emit("DXF", filename)
  8826. self.file_saved.emit("DXF", filename)
  8827. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8828. except Exception:
  8829. return 'fail'
  8830. if use_thread is True:
  8831. with self.proc_container.new(_("Exporting DXF")) as proc:
  8832. def job_thread_exc(app_obj):
  8833. ret_dxf_val = make_dxf()
  8834. if ret_dxf_val == 'fail':
  8835. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8836. return
  8837. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8838. else:
  8839. ret = make_dxf()
  8840. if ret == 'fail':
  8841. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8842. return
  8843. def import_svg(self, filename, geo_type='geometry', outname=None):
  8844. """
  8845. Adds a new Geometry Object to the projects and populates
  8846. it with shapes extracted from the SVG file.
  8847. :param filename: Path to the SVG file.
  8848. :param geo_type: Type of FlatCAM object that will be created from SVG
  8849. :param outname:
  8850. :return:
  8851. """
  8852. self.report_usage("import_svg()")
  8853. log.debug("App.import_svg()")
  8854. obj_type = ""
  8855. if geo_type is None or geo_type == "geometry":
  8856. obj_type = "geometry"
  8857. elif geo_type == "gerber":
  8858. obj_type = "gerber"
  8859. else:
  8860. self.inform.emit('[ERROR_NOTCL] %s' %
  8861. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8862. return
  8863. units = self.defaults['units'].upper()
  8864. def obj_init(geo_obj, app_obj):
  8865. geo_obj.import_svg(filename, obj_type, units=units)
  8866. geo_obj.multigeo = False
  8867. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8868. with self.proc_container.new(_("Importing SVG")) as proc:
  8869. # Object name
  8870. name = outname or filename.split('/')[-1].split('\\')[-1]
  8871. self.new_object(obj_type, name, obj_init, autoselected=False)
  8872. # Register recent file
  8873. self.file_opened.emit("svg", filename)
  8874. # GUI feedback
  8875. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8876. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8877. """
  8878. Adds a new Geometry Object to the projects and populates
  8879. it with shapes extracted from the DXF file.
  8880. :param filename: Path to the DXF file.
  8881. :param geo_type: Type of FlatCAM object that will be created from DXF
  8882. :param outname:
  8883. :type putname: str
  8884. :return:
  8885. """
  8886. self.report_usage("import_dxf()")
  8887. obj_type = ""
  8888. if geo_type is None or geo_type == "geometry":
  8889. obj_type = "geometry"
  8890. elif geo_type == "gerber":
  8891. obj_type = geo_type
  8892. else:
  8893. self.inform.emit('[ERROR_NOTCL] %s' %
  8894. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8895. return
  8896. units = self.defaults['units'].upper()
  8897. def obj_init(geo_obj, app_obj):
  8898. geo_obj.import_dxf(filename, obj_type, units=units)
  8899. geo_obj.multigeo = False
  8900. with self.proc_container.new(_("Importing DXF")) as proc:
  8901. # Object name
  8902. name = outname or filename.split('/')[-1].split('\\')[-1]
  8903. self.new_object(obj_type, name, obj_init, autoselected=False)
  8904. self.progress.emit(20)
  8905. # Register recent file
  8906. self.file_opened.emit("dxf", filename)
  8907. # GUI feedback
  8908. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8909. self.progress.emit(100)
  8910. def open_gerber(self, filename, outname=None):
  8911. """
  8912. Opens a Gerber file, parses it and creates a new object for
  8913. it in the program. Thread-safe.
  8914. :param outname: Name of the resulting object. None causes the
  8915. name to be that of the file.
  8916. :param filename: Gerber file filename
  8917. :type filename: str
  8918. :return: None
  8919. """
  8920. # How the object should be initialized
  8921. def obj_init(gerber_obj, app_obj):
  8922. assert isinstance(gerber_obj, FlatCAMGerber), \
  8923. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8924. # Opening the file happens here
  8925. try:
  8926. gerber_obj.parse_file(filename)
  8927. except IOError:
  8928. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8929. return "fail"
  8930. except ParseError as err:
  8931. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8932. app_obj.log.error(str(err))
  8933. return "fail"
  8934. except Exception as e:
  8935. log.debug("App.open_gerber() --> %s" % str(e))
  8936. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8937. msg += traceback.format_exc()
  8938. app_obj.inform.emit(msg)
  8939. return "fail"
  8940. if gerber_obj.is_empty():
  8941. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8942. _("Object is not Gerber file or empty. Aborting object creation."))
  8943. return "fail"
  8944. App.log.debug("open_gerber()")
  8945. with self.proc_container.new(_("Opening Gerber")) as proc:
  8946. # Object name
  8947. name = outname or filename.split('/')[-1].split('\\')[-1]
  8948. # # ## Object creation # ##
  8949. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8950. if ret == 'fail':
  8951. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8952. return 'fail'
  8953. # Register recent file
  8954. self.file_opened.emit("gerber", filename)
  8955. # GUI feedback
  8956. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8957. def open_excellon(self, filename, outname=None, plot=True):
  8958. """
  8959. Opens an Excellon file, parses it and creates a new object for
  8960. it in the program. Thread-safe.
  8961. :param outname: Name of the resulting object. None causes the
  8962. name to be that of the file.
  8963. :param filename: Excellon file filename
  8964. :type filename: str
  8965. :return: None
  8966. """
  8967. App.log.debug("open_excellon()")
  8968. # How the object should be initialized
  8969. def obj_init(excellon_obj, app_obj):
  8970. # self.progress.emit(20)
  8971. try:
  8972. ret = excellon_obj.parse_file(filename=filename)
  8973. if ret == "fail":
  8974. log.debug("Excellon parsing failed.")
  8975. self.inform.emit('[ERROR_NOTCL] %s' %
  8976. _("This is not Excellon file."))
  8977. return "fail"
  8978. except IOError:
  8979. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8980. (_("Cannot open file"), filename))
  8981. log.debug("Could not open Excellon object.")
  8982. self.progress.emit(0) # TODO: self and app_bjj mixed
  8983. return "fail"
  8984. except Exception:
  8985. msg = '[ERROR_NOTCL] %s' % \
  8986. _("An internal error has occurred. See shell.\n")
  8987. msg += traceback.format_exc()
  8988. app_obj.inform.emit(msg)
  8989. return "fail"
  8990. ret = excellon_obj.create_geometry()
  8991. if ret == 'fail':
  8992. log.debug("Could not create geometry for Excellon object.")
  8993. return "fail"
  8994. for tool in excellon_obj.tools:
  8995. if excellon_obj.tools[tool]['solid_geometry']:
  8996. return
  8997. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8998. (_("No geometry found in file"), filename))
  8999. return "fail"
  9000. with self.proc_container.new(_("Opening Excellon.")):
  9001. # Object name
  9002. name = outname or filename.split('/')[-1].split('\\')[-1]
  9003. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9004. if ret_val == 'fail':
  9005. self.inform.emit('[ERROR_NOTCL] %s' %
  9006. _('Open Excellon file failed. Probable not an Excellon file.'))
  9007. return
  9008. # Register recent file
  9009. self.file_opened.emit("excellon", filename)
  9010. # GUI feedback
  9011. self.inform.emit('[success] %s: %s' %
  9012. (_("Opened"), filename))
  9013. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9014. """
  9015. Opens a G-gcode file, parses it and creates a new object for
  9016. it in the program. Thread-safe.
  9017. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9018. :param filename: G-code file filename
  9019. :type filename: str
  9020. :return: None
  9021. """
  9022. App.log.debug("open_gcode()")
  9023. # How the object should be initialized
  9024. def obj_init(job_obj, app_obj_):
  9025. """
  9026. :param job_obj: the resulting object
  9027. :type app_obj_: App
  9028. """
  9029. assert isinstance(app_obj_, App), \
  9030. "Initializer expected App, got %s" % type(app_obj_)
  9031. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9032. try:
  9033. f = open(filename)
  9034. gcode = f.read()
  9035. f.close()
  9036. except IOError:
  9037. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9038. (_("Failed to open"), filename))
  9039. return "fail"
  9040. job_obj.gcode = gcode
  9041. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9042. if gcode_ret == "fail":
  9043. self.inform.emit('[ERROR_NOTCL] %s' %
  9044. _("This is not GCODE"))
  9045. return "fail"
  9046. job_obj.create_geometry()
  9047. with self.proc_container.new(_("Opening G-Code.")):
  9048. # Object name
  9049. name = outname or filename.split('/')[-1].split('\\')[-1]
  9050. # New object creation and file processing
  9051. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9052. if obj_ret == 'fail':
  9053. self.inform.emit('[ERROR_NOTCL] %s' %
  9054. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9055. "Try to load it from File menu.\n "
  9056. "Attempting to create a FlatCAM CNCJob Object from "
  9057. "G-Code file failed during processing"))
  9058. return "fail"
  9059. # Register recent file
  9060. self.file_opened.emit("cncjob", filename)
  9061. # GUI feedback
  9062. self.inform.emit('[success] %s: %s' %
  9063. (_("Opened"), filename))
  9064. def open_script(self, filename, outname=None, silent=False):
  9065. """
  9066. Opens a Script file, parses it and creates a new object for
  9067. it in the program. Thread-safe.
  9068. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9069. :param filename: Script file filename
  9070. :type filename: str
  9071. :return: None
  9072. """
  9073. App.log.debug("open_script()")
  9074. with self.proc_container.new(_("Opening TCL Script...")):
  9075. try:
  9076. with open(filename, "r") as opened_script:
  9077. script_content = opened_script.readlines()
  9078. script_content = ''.join(script_content)
  9079. if silent is False:
  9080. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9081. except Exception as e:
  9082. log.debug("App.open_script() -> %s" % str(e))
  9083. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9084. return
  9085. # Object name
  9086. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9087. # New object creation and file processing
  9088. self.on_filenewscript(name=script_name, text=script_content)
  9089. # Register recent file
  9090. self.file_opened.emit("script", filename)
  9091. # GUI feedback
  9092. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9093. def open_config_file(self, filename, run_from_arg=None):
  9094. """
  9095. Loads a config file from the specified file.
  9096. :param filename: Name of the file from which to load.
  9097. :type filename: str
  9098. :return: None
  9099. """
  9100. App.log.debug("Opening config file: " + filename)
  9101. if run_from_arg:
  9102. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9103. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9104. _("Opening FlatCAM Config file.")),
  9105. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9106. color=QtGui.QColor("gray"))
  9107. # # add the tab if it was closed
  9108. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9109. # # first clear previous text in text editor (if any)
  9110. # self.ui.text_editor_tab.code_editor.clear()
  9111. #
  9112. # # Switch plot_area to CNCJob tab
  9113. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9114. # close the Code editor if already open
  9115. if self.toggle_codeeditor:
  9116. self.on_toggle_code_editor()
  9117. self.on_toggle_code_editor()
  9118. try:
  9119. if filename:
  9120. f = QtCore.QFile(filename)
  9121. if f.open(QtCore.QIODevice.ReadOnly):
  9122. stream = QtCore.QTextStream(f)
  9123. code_edited = stream.readAll()
  9124. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9125. f.close()
  9126. except IOError:
  9127. App.log.error("Failed to open config file: %s" % filename)
  9128. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9129. (_("Failed to open config file"), filename))
  9130. return
  9131. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9132. """
  9133. Loads a project from the specified file.
  9134. 1) Loads and parses file
  9135. 2) Registers the file as recently opened.
  9136. 3) Calls on_file_new()
  9137. 4) Updates options
  9138. 5) Calls new_object() with the object's from_dict() as init method.
  9139. 6) Calls plot_all() if plot=True
  9140. :param filename: Name of the file from which to load.
  9141. :type filename: str
  9142. :param run_from_arg: True if run for arguments
  9143. :param plot: If True plot all objects in the project
  9144. :param cli: run from command line
  9145. :return: None
  9146. """
  9147. App.log.debug("Opening project: " + filename)
  9148. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9149. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9150. if cli is None:
  9151. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9152. if run_from_arg:
  9153. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9154. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9155. _("Opening FlatCAM Project file.")),
  9156. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9157. color=QtGui.QColor("gray"))
  9158. # Open and parse an uncompressed Project file
  9159. try:
  9160. f = open(filename, 'r')
  9161. except IOError:
  9162. App.log.error("Failed to open project file: %s" % filename)
  9163. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9164. (_("Failed to open project file"), filename))
  9165. return
  9166. try:
  9167. d = json.load(f, object_hook=dict2obj)
  9168. except Exception as e:
  9169. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9170. (filename, str(e)))
  9171. f.close()
  9172. # Open and parse a compressed Project file
  9173. try:
  9174. with lzma.open(filename) as f:
  9175. file_content = f.read().decode('utf-8')
  9176. d = json.loads(file_content, object_hook=dict2obj)
  9177. except Exception as e:
  9178. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9179. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9180. (_("Failed to open project file"), filename))
  9181. return
  9182. # Clear the current project
  9183. # # NOT THREAD SAFE # ##
  9184. if run_from_arg is True:
  9185. pass
  9186. elif cli is True:
  9187. self.delete_selection_shape()
  9188. else:
  9189. self.on_file_new()
  9190. # Project options
  9191. self.options.update(d['options'])
  9192. self.project_filename = filename
  9193. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9194. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9195. if cli is None:
  9196. self.set_screen_units(self.options["units"])
  9197. # Re create objects
  9198. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9199. for obj in d['objs']:
  9200. def obj_init(obj_inst, app_inst):
  9201. obj_inst.from_dict(obj)
  9202. App.log.debug("Recreating from opened project an %s object: %s" %
  9203. (obj['kind'].capitalize(), obj['options']['name']))
  9204. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9205. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9206. if cli is None:
  9207. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9208. obj['kind'].upper(),
  9209. obj['options']['name']
  9210. )
  9211. )
  9212. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9213. self.inform.emit('[success] %s: %s' %
  9214. (_("Project loaded from"), filename))
  9215. self.should_we_save = False
  9216. self.file_opened.emit("project", filename)
  9217. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9218. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9219. if cli is None:
  9220. self.set_ui_title(name=self.project_filename)
  9221. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9222. def propagate_defaults(self, silent=False):
  9223. """
  9224. This method is used to set default values in classes. It's
  9225. an alternative to project options but allows the use
  9226. of values invisible to the user.
  9227. :return: None
  9228. """
  9229. if silent is False:
  9230. self.log.debug("propagate_defaults()")
  9231. # Which objects to update the given parameters.
  9232. routes = {
  9233. "global_zdownrate": CNCjob,
  9234. "excellon_zeros": Excellon,
  9235. "excellon_format_upper_in": Excellon,
  9236. "excellon_format_lower_in": Excellon,
  9237. "excellon_format_upper_mm": Excellon,
  9238. "excellon_format_lower_mm": Excellon,
  9239. "excellon_units": Excellon,
  9240. "gerber_use_buffer_for_union": Gerber,
  9241. "geometry_multidepth": Geometry
  9242. }
  9243. for param in routes:
  9244. if param in routes[param].defaults:
  9245. try:
  9246. routes[param].defaults[param] = self.defaults[param]
  9247. if silent is False:
  9248. self.log.debug(" " + param + " OK")
  9249. except KeyError:
  9250. if silent is False:
  9251. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9252. else:
  9253. # Try extracting the name:
  9254. # classname_param here is param in the object
  9255. if param.find(routes[param].__name__.lower() + "_") == 0:
  9256. p = param[len(routes[param].__name__) + 1:]
  9257. if p in routes[param].defaults:
  9258. routes[param].defaults[p] = self.defaults[param]
  9259. if silent is False:
  9260. self.log.debug(" " + param + " OK!")
  9261. def plot_all(self, zoom=True):
  9262. """
  9263. Re-generates all plots from all objects.
  9264. :return: None
  9265. """
  9266. self.log.debug("Plot_all()")
  9267. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9268. for obj in self.collection.get_list():
  9269. def worker_task(obj):
  9270. with self.proc_container.new("Plotting"):
  9271. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9272. if zoom:
  9273. self.object_plotted.emit(obj)
  9274. # Send to worker
  9275. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9276. def register_folder(self, filename):
  9277. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9278. def register_save_folder(self, filename):
  9279. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9280. def set_progress_bar(self, percentage, text=""):
  9281. self.ui.progress_bar.setValue(int(percentage))
  9282. def setup_shell(self):
  9283. """
  9284. Creates shell functions. Runs once at startup.
  9285. :return: None
  9286. """
  9287. self.log.debug("setup_shell()")
  9288. def shelp(p=None):
  9289. if not p:
  9290. return _("Available commands:\n") + \
  9291. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9292. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9293. if p not in commands:
  9294. return "Unknown command: %s" % p
  9295. return commands[p]["help"]
  9296. # --- Migrated to new architecture ---
  9297. # def options(name):
  9298. # ops = self.collection.get_by_name(str(name)).options
  9299. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9300. def h(*args):
  9301. """
  9302. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9303. and standalone parameters into list.
  9304. """
  9305. kwa = {}
  9306. a = []
  9307. n = len(args)
  9308. name = None
  9309. for i in range(n):
  9310. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9311. if match:
  9312. assert name is None
  9313. name = match.group(1)
  9314. continue
  9315. if name is None:
  9316. a.append(args[i])
  9317. else:
  9318. kwa[name] = args[i]
  9319. name = None
  9320. return a, kwa
  9321. @contextmanager
  9322. def wait_signal(signal, timeout=10000):
  9323. """
  9324. Block loop until signal emitted, timeout (ms) elapses
  9325. or unhandled exception happens in a thread.
  9326. :param timeout: time after which the loop is exited
  9327. :param signal: Signal to wait for.
  9328. """
  9329. loop = QtCore.QEventLoop()
  9330. # Normal termination
  9331. signal.connect(loop.quit)
  9332. # Termination by exception in thread
  9333. self.thread_exception.connect(loop.quit)
  9334. status = {'timed_out': False}
  9335. def report_quit():
  9336. status['timed_out'] = True
  9337. loop.quit()
  9338. yield
  9339. # Temporarily change how exceptions are managed.
  9340. oeh = sys.excepthook
  9341. ex = []
  9342. def except_hook(type_, value, traceback_):
  9343. ex.append(value)
  9344. oeh(type_, value, traceback_)
  9345. sys.excepthook = except_hook
  9346. # Terminate on timeout
  9347. if timeout is not None:
  9348. QtCore.QTimer.singleShot(timeout, report_quit)
  9349. # # ## Block ## ##
  9350. loop.exec_()
  9351. # Restore exception management
  9352. sys.excepthook = oeh
  9353. if ex:
  9354. self.raiseTclError(str(ex[0]))
  9355. if status['timed_out']:
  9356. raise Exception('Timed out!')
  9357. def make_docs():
  9358. output = ''
  9359. import collections
  9360. od = collections.OrderedDict(sorted(commands.items()))
  9361. for cmd_, val in od.items():
  9362. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9363. t = val['help']
  9364. usage_i = t.find('>')
  9365. if usage_i < 0:
  9366. expl = t
  9367. output += expl + '\n\n'
  9368. continue
  9369. expl = t[:usage_i - 1]
  9370. output += expl + '\n\n'
  9371. end_usage_i = t[usage_i:].find('\n')
  9372. if end_usage_i < 0:
  9373. end_usage_i = len(t[usage_i:])
  9374. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9375. else:
  9376. extras = t[usage_i+end_usage_i+1:]
  9377. parts = [s.strip() for s in extras.split('\n')]
  9378. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9379. for p in parts:
  9380. output += ' ' + p + '\n\n'
  9381. return output
  9382. '''
  9383. Howto implement TCL shell commands:
  9384. All parameters passed to command should be possible to set as None and test it afterwards.
  9385. This is because we need to see error caused in tcl,
  9386. if None value as default parameter is not allowed TCL will return empty error.
  9387. Use:
  9388. def mycommand(name=None,...):
  9389. Test it like this:
  9390. if name is None:
  9391. self.raise_tcl_error('Argument name is missing.')
  9392. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9393. otherwise we will miss it and processing will silently continue.
  9394. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9395. which is catched in exec_command and displayed in TCL shell console with red background.
  9396. Error in console is displayed with TCL trace.
  9397. This behavior works only within main thread,
  9398. errors with promissed tasks can be catched and detected only with log.
  9399. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9400. TCL shell.
  9401. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9402. '''
  9403. commands = {
  9404. 'help': {
  9405. 'fcn': shelp,
  9406. 'help': _("Shows list of commands.")
  9407. },
  9408. }
  9409. # Import/overwrite tcl commands as objects of TclCommand descendants
  9410. # This modifies the variable 'commands'.
  9411. tclCommands.register_all_commands(self, commands)
  9412. # Add commands to the tcl interpreter
  9413. for cmd in commands:
  9414. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9415. # Make the tcl puts function return instead of print to stdout
  9416. self.tcl.eval('''
  9417. rename puts original_puts
  9418. proc puts {args} {
  9419. if {[llength $args] == 1} {
  9420. return "[lindex $args 0]"
  9421. } else {
  9422. eval original_puts $args
  9423. }
  9424. }
  9425. ''')
  9426. def setup_recent_items(self):
  9427. # TODO: Move this to constructor
  9428. icons = {
  9429. "gerber": "share/flatcam_icon16.png",
  9430. "excellon": "share/drill16.png",
  9431. 'geometry': "share/geometry16.png",
  9432. "cncjob": "share/cnc16.png",
  9433. "script": "share/script_new24.png",
  9434. "document": "share/notes16_1.png",
  9435. "project": "share/project16.png",
  9436. "svg": "share/geometry16.png",
  9437. "dxf": "share/dxf16.png",
  9438. "pdf": "share/pdf32.png",
  9439. "image": "share/image16.png"
  9440. }
  9441. openers = {
  9442. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9443. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9444. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9445. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9446. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9447. "document": None,
  9448. 'project': self.open_project,
  9449. 'svg': self.import_svg,
  9450. 'dxf': self.import_dxf,
  9451. 'image': self.image_tool.import_image,
  9452. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9453. }
  9454. # Open recent file for files
  9455. try:
  9456. f = open(self.data_path + '/recent.json')
  9457. except IOError:
  9458. App.log.error("Failed to load recent item list.")
  9459. self.inform.emit('[ERROR_NOTCL] %s' %
  9460. _("Failed to load recent item list."))
  9461. return
  9462. try:
  9463. self.recent = json.load(f)
  9464. except json.scanner.JSONDecodeError:
  9465. App.log.error("Failed to parse recent item list.")
  9466. self.inform.emit('[ERROR_NOTCL] %s' %
  9467. _("Failed to parse recent item list."))
  9468. f.close()
  9469. return
  9470. f.close()
  9471. # Open recent file for projects
  9472. try:
  9473. fp = open(self.data_path + '/recent_projects.json')
  9474. except IOError:
  9475. App.log.error("Failed to load recent project item list.")
  9476. self.inform.emit('[ERROR_NOTCL] %s' %
  9477. _("Failed to load recent projects item list."))
  9478. return
  9479. try:
  9480. self.recent_projects = json.load(fp)
  9481. except json.scanner.JSONDecodeError:
  9482. App.log.error("Failed to parse recent project item list.")
  9483. self.inform.emit('[ERROR_NOTCL] %s' %
  9484. _("Failed to parse recent project item list."))
  9485. fp.close()
  9486. return
  9487. fp.close()
  9488. # Closure needed to create callbacks in a loop.
  9489. # Otherwise late binding occurs.
  9490. def make_callback(func, fname):
  9491. def opener():
  9492. func(fname)
  9493. return opener
  9494. def reset_recent_files():
  9495. # Reset menu
  9496. self.ui.recent.clear()
  9497. self.recent = []
  9498. try:
  9499. ff = open(self.data_path + '/recent.json', 'w')
  9500. except IOError:
  9501. App.log.error("Failed to open recent items file for writing.")
  9502. return
  9503. json.dump(self.recent, ff)
  9504. def reset_recent_projects():
  9505. # Reset menu
  9506. self.ui.recent_projects.clear()
  9507. self.recent_projects = []
  9508. try:
  9509. fp = open(self.data_path + '/recent_projects.json', 'w')
  9510. except IOError:
  9511. App.log.error("Failed to open recent projects items file for writing.")
  9512. return
  9513. json.dump(self.recent, fp)
  9514. # Reset menu
  9515. self.ui.recent.clear()
  9516. self.ui.recent_projects.clear()
  9517. # Create menu items for projects
  9518. for recent in self.recent_projects:
  9519. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9520. if recent['kind'] == 'project':
  9521. try:
  9522. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9523. # Attach callback
  9524. o = make_callback(openers[recent["kind"]], recent['filename'])
  9525. action.triggered.connect(o)
  9526. self.ui.recent_projects.addAction(action)
  9527. except KeyError:
  9528. App.log.error("Unsupported file type: %s" % recent["kind"])
  9529. # Last action in Recent Files menu is one that Clear the content
  9530. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9531. clear_action_proj.triggered.connect(reset_recent_projects)
  9532. self.ui.recent_projects.addSeparator()
  9533. self.ui.recent_projects.addAction(clear_action_proj)
  9534. # Create menu items for files
  9535. for recent in self.recent:
  9536. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9537. if recent['kind'] != 'project':
  9538. try:
  9539. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9540. # Attach callback
  9541. o = make_callback(openers[recent["kind"]], recent['filename'])
  9542. action.triggered.connect(o)
  9543. self.ui.recent.addAction(action)
  9544. except KeyError:
  9545. App.log.error("Unsupported file type: %s" % recent["kind"])
  9546. # Last action in Recent Files menu is one that Clear the content
  9547. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9548. clear_action.triggered.connect(reset_recent_files)
  9549. self.ui.recent.addSeparator()
  9550. self.ui.recent.addAction(clear_action)
  9551. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9552. # self.ui.menufilerecent.set_submenu(recent_menu)
  9553. # recent_menu.show_all()
  9554. # self.ui.recent.show()
  9555. self.log.debug("Recent items list has been populated.")
  9556. def setup_component_editor(self):
  9557. # label = QtWidgets.QLabel("Choose an item from Project")
  9558. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9559. sel_title = QtWidgets.QTextEdit(
  9560. _('<b>Shortcut Key List</b>'))
  9561. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9562. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9563. settings = QSettings("Open Source", "FlatCAM")
  9564. if settings.contains("notebook_font_size"):
  9565. fsize = settings.value('notebook_font_size', type=int)
  9566. else:
  9567. fsize = 12
  9568. tsize = fsize + int(fsize / 2)
  9569. # selected_text = (_('''
  9570. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9571. #
  9572. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9573. # The normal flow when working in FlatCAM is the following:</span></p>
  9574. #
  9575. # <ol>
  9576. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9577. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9578. # even dragging and dropping the files on the GUI.<br />
  9579. # <br />
  9580. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9581. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9582. # &nbsp;</li>
  9583. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9584. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9585. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9586. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9587. # <br />
  9588. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9589. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9590. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9591. # it even if it was out of focus.<br />
  9592. # <br />
  9593. # You can change the parameters in this screen and the flow direction is like this:<br />
  9594. # <br />
  9595. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9596. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9597. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9598. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9599. # </ol>
  9600. #
  9601. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9602. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9603. # <strong>F3</strong>.</span></p>
  9604. #
  9605. # ''').format(fsize=fsize, tsize=tsize))
  9606. selected_text = '''
  9607. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9608. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9609. {s1}</span></p>
  9610. <ol>
  9611. <li><span style="font-size:{fsize}px">{s2}<br />
  9612. <br />
  9613. {s3}</span><br />
  9614. &nbsp;</li>
  9615. <li><span style="font-size:{fsize}px">{s4}<br />
  9616. &nbsp;</li>
  9617. <br />
  9618. <li><span style="font-size:{fsize}px">{s5}<br />
  9619. &nbsp;</li>
  9620. <br />
  9621. <li><span style="font-size:{fsize}px">{s6}<br />
  9622. <br />
  9623. {s7}</span></li>
  9624. </ol>
  9625. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9626. '''.format(
  9627. title=_("Selected Tab - Choose an Item from Project Tab"),
  9628. subtitle=_("Details"),
  9629. s1=_("The normal flow when working in FlatCAM is the following:"),
  9630. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9631. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9632. "files on the GUI."),
  9633. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9634. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9635. "actions offered within the app."),
  9636. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9637. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9638. "SELECTED TAB will be updated with the object properties according to its kind: "
  9639. "Gerber, Excellon, Geometry or CNCJob object."),
  9640. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9641. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9642. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9643. "the SELECTED TAB and populate it even if it was out of focus."),
  9644. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9645. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9646. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9647. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9648. "(again, done in SELECTED TAB) --> Save GCode."),
  9649. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9650. "or through its own key shortcut: <b>F3</b>."),
  9651. tsize=tsize,
  9652. fsize=fsize
  9653. )
  9654. sel_title.setText(selected_text)
  9655. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9656. self.ui.selected_scroll_area.setWidget(sel_title)
  9657. def setup_obj_classes(self):
  9658. """
  9659. Sets up application specifics on the FlatCAMObj class.
  9660. :return: None
  9661. """
  9662. FlatCAMObj.app = self
  9663. ObjectCollection.app = self
  9664. Gerber.app = self
  9665. Excellon.app = self
  9666. Geometry.app = self
  9667. CNCjob.app = self
  9668. FCProcess.app = self
  9669. FCProcessContainer.app = self
  9670. def version_check(self):
  9671. """
  9672. Checks for the latest version of the program. Alerts the
  9673. user if theirs is outdated. This method is meant to be run
  9674. in a separate thread.
  9675. :return: None
  9676. """
  9677. self.log.debug("version_check()")
  9678. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9679. full_url = App.version_url + \
  9680. "?s=" + str(self.defaults['global_serial']) + \
  9681. "&v=" + str(self.version) + \
  9682. "&os=" + str(self.os) + \
  9683. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9684. else:
  9685. # no_stats dict; just so it won't break things on website
  9686. no_ststs_dict = {}
  9687. no_ststs_dict["global_ststs"] = {}
  9688. full_url = App.version_url + \
  9689. "?s=" + str(self.defaults['global_serial']) + \
  9690. "&v=" + str(self.version) + \
  9691. "&os=" + str(self.os) + \
  9692. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9693. App.log.debug("Checking for updates @ %s" % full_url)
  9694. # ## Get the data
  9695. try:
  9696. f = urllib.request.urlopen(full_url)
  9697. except Exception:
  9698. # App.log.warning("Failed checking for latest version. Could not connect.")
  9699. self.log.warning("Failed checking for latest version. Could not connect.")
  9700. self.inform.emit('[WARNING_NOTCL] %s' %
  9701. _("Failed checking for latest version. Could not connect."))
  9702. return
  9703. try:
  9704. data = json.load(f)
  9705. except Exception as e:
  9706. App.log.error("Could not parse information about latest version.")
  9707. self.inform.emit('[ERROR_NOTCL] %s' %
  9708. _("Could not parse information about latest version."))
  9709. App.log.debug("json.load(): %s" % str(e))
  9710. f.close()
  9711. return
  9712. f.close()
  9713. # ## Latest version?
  9714. if self.version >= data["version"]:
  9715. App.log.debug("FlatCAM is up to date!")
  9716. self.inform.emit('[success] %s' %
  9717. _("FlatCAM is up to date!"))
  9718. return
  9719. App.log.debug("Newer version available.")
  9720. self.message.emit(
  9721. _("Newer Version Available"),
  9722. _("There is a newer version of FlatCAM available for download:\n\n") +
  9723. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9724. _("info")
  9725. )
  9726. def on_plotcanvas_setup(self, container=None):
  9727. """
  9728. This is doing the setup for the plot area (VisPy canvas)
  9729. :param container: widget where to install the canvas
  9730. :return: None
  9731. """
  9732. if container:
  9733. plot_container = container
  9734. else:
  9735. plot_container = self.ui.right_layout
  9736. if self.is_legacy is False:
  9737. self.plotcanvas = PlotCanvas(plot_container, self)
  9738. else:
  9739. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9740. # So it can receive key presses
  9741. self.plotcanvas.native.setFocus()
  9742. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9743. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9744. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9745. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9746. # Keys over plot enabled
  9747. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9748. if self.defaults['global_cursor_type'] == 'small':
  9749. self.app_cursor = self.plotcanvas.new_cursor()
  9750. else:
  9751. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9752. if self.ui.grid_snap_btn.isChecked():
  9753. self.app_cursor.enabled = True
  9754. else:
  9755. self.app_cursor.enabled = False
  9756. if self.is_legacy is False:
  9757. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9758. else:
  9759. # will use the default Matplotlib axes
  9760. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9761. def on_zoom_fit(self, event):
  9762. """
  9763. Callback for zoom-out request. This can be either from the corresponding
  9764. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9765. with axes limits from the geometry bounds of all objects.
  9766. :param event: Ignored.
  9767. :return: None
  9768. """
  9769. if self.is_legacy is False:
  9770. self.plotcanvas.fit_view()
  9771. else:
  9772. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9773. width = xmax - xmin
  9774. height = ymax - ymin
  9775. xmin -= 0.05 * width
  9776. xmax += 0.05 * width
  9777. ymin -= 0.05 * height
  9778. ymax += 0.05 * height
  9779. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9780. def on_zoom_in(self):
  9781. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9782. def on_zoom_out(self):
  9783. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9784. def disable_all_plots(self):
  9785. self.report_usage("disable_all_plots()")
  9786. self.disable_plots(self.collection.get_list())
  9787. self.inform.emit('[success] %s' %
  9788. _("All plots disabled."))
  9789. def disable_other_plots(self):
  9790. self.report_usage("disable_other_plots()")
  9791. self.disable_plots(self.collection.get_non_selected())
  9792. self.inform.emit('[success] %s' %
  9793. _("All non selected plots disabled."))
  9794. def enable_all_plots(self):
  9795. self.report_usage("enable_all_plots()")
  9796. self.enable_plots(self.collection.get_list())
  9797. self.inform.emit('[success] %s' %
  9798. _("All plots enabled."))
  9799. def on_enable_sel_plots(self):
  9800. log.debug("App.on_enable_sel_plot()")
  9801. object_list = self.collection.get_selected()
  9802. self.enable_plots(objects=object_list)
  9803. self.inform.emit('[success] %s' %
  9804. _("Selected plots enabled..."))
  9805. def on_disable_sel_plots(self):
  9806. log.debug("App.on_disable_sel_plot()")
  9807. # self.inform.emit(_("Disabling plots ..."))
  9808. object_list = self.collection.get_selected()
  9809. self.disable_plots(objects=object_list)
  9810. self.inform.emit('[success] %s' %
  9811. _("Selected plots disabled..."))
  9812. def enable_plots(self, objects):
  9813. """
  9814. Disables plots
  9815. :param objects: list of Objects to be enabled
  9816. :return:
  9817. """
  9818. log.debug("Enabling plots ...")
  9819. # self.inform.emit(_("Working ..."))
  9820. for obj in objects:
  9821. if obj.options['plot'] is False:
  9822. obj.options.set_change_callback(lambda x: None)
  9823. obj.options['plot'] = True
  9824. obj.options.set_change_callback(obj.on_options_change)
  9825. def worker_task(objs):
  9826. with self.proc_container.new(_("Enabling plots ...")):
  9827. for obj in objs:
  9828. # obj.options['plot'] = True
  9829. if isinstance(obj, FlatCAMCNCjob):
  9830. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9831. else:
  9832. obj.plot(visible=True)
  9833. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9834. # self.plots_updated.emit()
  9835. def disable_plots(self, objects):
  9836. """
  9837. Disables plots
  9838. :param objects: list of Objects to be disabled
  9839. :return:
  9840. """
  9841. # if no objects selected then do nothing
  9842. if not self.collection.get_selected():
  9843. return
  9844. log.debug("Disabling plots ...")
  9845. # self.inform.emit(_("Working ..."))
  9846. for obj in objects:
  9847. if obj.options['plot'] is True:
  9848. obj.options.set_change_callback(lambda x: None)
  9849. obj.options['plot'] = False
  9850. obj.options.set_change_callback(obj.on_options_change)
  9851. try:
  9852. self.delete_selection_shape()
  9853. except Exception as e:
  9854. log.debug("App.disable_plots() --> %s" % str(e))
  9855. # self.plots_updated.emit()
  9856. def worker_task(objs):
  9857. with self.proc_container.new(_("Disabling plots ...")):
  9858. for obj in objs:
  9859. # obj.options['plot'] = True
  9860. if isinstance(obj, FlatCAMCNCjob):
  9861. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9862. else:
  9863. obj.plot(visible=False)
  9864. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9865. def toggle_plots(self, objects):
  9866. """
  9867. Toggle plots visibility
  9868. :param objects: list of Objects for which to be toggled the visibility
  9869. :return:
  9870. """
  9871. # if no objects selected then do nothing
  9872. if not self.collection.get_selected():
  9873. return
  9874. log.debug("Toggling plots ...")
  9875. self.inform.emit(_("Working ..."))
  9876. for obj in objects:
  9877. if obj.options['plot'] is False:
  9878. obj.options['plot'] = True
  9879. else:
  9880. obj.options['plot'] = False
  9881. self.plots_updated.emit()
  9882. def clear_plots(self):
  9883. objects = self.collection.get_list()
  9884. for obj in objects:
  9885. obj.clear(obj == objects[-1])
  9886. # Clear pool to free memory
  9887. self.clear_pool()
  9888. def generate_cnc_job(self, objects):
  9889. self.report_usage("generate_cnc_job()")
  9890. # for obj in objects:
  9891. # obj.generatecncjob()
  9892. for obj in objects:
  9893. obj.on_generatecnc_button_click()
  9894. def save_project(self, filename, quit_action=False, silent=False):
  9895. """
  9896. Saves the current project to the specified file.
  9897. :param filename: Name of the file in which to save.
  9898. :type filename: str
  9899. :param quit_action: if the project saving will be followed by an app quit; boolean
  9900. :param silent: if True will not display status messages
  9901. :return: None
  9902. """
  9903. self.log.debug("save_project()")
  9904. self.save_in_progress = True
  9905. with self.proc_container.new(_("Saving FlatCAM Project")):
  9906. # Capture the latest changes
  9907. # Current object
  9908. try:
  9909. self.collection.get_active().read_form()
  9910. except Exception as e:
  9911. self.log.debug("There was no active object. %s" % str(e))
  9912. pass
  9913. # Serialize the whole project
  9914. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9915. "options": self.options,
  9916. "version": self.version}
  9917. if self.defaults["global_save_compressed"] is True:
  9918. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9919. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9920. # # Write
  9921. f.write(g)
  9922. self.inform.emit('[success] %s: %s' %
  9923. (_("Project saved to"), filename))
  9924. else:
  9925. # Open file
  9926. try:
  9927. f = open(filename, 'w')
  9928. except IOError:
  9929. App.log.error("Failed to open file for saving: %s", filename)
  9930. return
  9931. # Write
  9932. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9933. f.close()
  9934. # verification of the saved project
  9935. # Open and parse
  9936. try:
  9937. saved_f = open(filename, 'r')
  9938. except IOError:
  9939. if silent is False:
  9940. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9941. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9942. )
  9943. return
  9944. try:
  9945. saved_d = json.load(saved_f, object_hook=dict2obj)
  9946. except Exception:
  9947. if silent is False:
  9948. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9949. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9950. )
  9951. f.close()
  9952. return
  9953. saved_f.close()
  9954. if silent is False:
  9955. if 'version' in saved_d:
  9956. self.inform.emit('[success] %s: %s' %
  9957. (_("Project saved to"), filename))
  9958. else:
  9959. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9960. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9961. )
  9962. tb_settings = QSettings("Open Source", "FlatCAM")
  9963. lock_state = self.ui.lock_action.isChecked()
  9964. tb_settings.setValue('toolbar_lock', lock_state)
  9965. # This will write the setting to the platform specific storage.
  9966. del tb_settings
  9967. # if quit:
  9968. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9969. # t.start()
  9970. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9971. def start_delayed_quit(self, delay, filename, should_quit=None):
  9972. """
  9973. :param delay: period of checking if project file size is more than zero; in seconds
  9974. :param filename: the name of the project file to be checked periodically for size more than zero
  9975. :param should_quit: if the task finished will be followed by an app quit; boolean
  9976. :return:
  9977. """
  9978. to_quit = should_quit
  9979. self.save_timer = QtCore.QTimer()
  9980. self.save_timer.setInterval(delay)
  9981. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9982. self.save_timer.start()
  9983. def check_project_file_size(self, filename, should_quit=None):
  9984. """
  9985. :param filename: the name of the project file to be checked periodically for size more than zero
  9986. :param should_quit: will quit the app if True; boolean
  9987. :return:
  9988. """
  9989. try:
  9990. if os.stat(filename).st_size > 0:
  9991. self.save_in_progress = False
  9992. self.save_timer.stop()
  9993. if should_quit:
  9994. self.app_quit.emit()
  9995. except Exception:
  9996. traceback.print_exc()
  9997. def on_plotarea_tab_closed(self, tab_idx):
  9998. widget = self.ui.plot_tab_area.widget(tab_idx)
  9999. if widget is not None:
  10000. widget.deleteLater()
  10001. self.ui.plot_tab_area.removeTab(tab_idx)
  10002. def on_options_app2project(self):
  10003. """
  10004. Callback for Options->Transfer Options->App=>Project. Copies options
  10005. from application defaults to project defaults.
  10006. :return: None
  10007. """
  10008. self.report_usage("on_options_app2project")
  10009. self.defaults_read_form()
  10010. self.options.update(self.defaults)
  10011. # self.options_write_form()
  10012. class ArgsThread(QtCore.QObject):
  10013. open_signal = pyqtSignal(list)
  10014. start = pyqtSignal()
  10015. if sys.platform == 'win32':
  10016. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10017. else:
  10018. address = ('/tmp/testipc', 'AF_UNIX')
  10019. def __init__(self):
  10020. super(ArgsThread, self).__init__()
  10021. self.start.connect(self.run)
  10022. def my_loop(self, address):
  10023. try:
  10024. listener = Listener(*address)
  10025. while True:
  10026. conn = listener.accept()
  10027. self.serve(conn)
  10028. except socket.error:
  10029. conn = Client(*address)
  10030. conn.send(sys.argv)
  10031. conn.send('close')
  10032. # close the current instance only if there are args
  10033. if len(sys.argv) > 1:
  10034. sys.exit()
  10035. def serve(self, conn):
  10036. while True:
  10037. msg = conn.recv()
  10038. if msg == 'close':
  10039. break
  10040. self.open_signal.emit(msg)
  10041. conn.close()
  10042. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10043. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10044. @pyqtSlot()
  10045. def run(self):
  10046. self.my_loop(self.address)
  10047. class GracefulException(Exception):
  10048. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10049. def __init__(self):
  10050. super().__init__()
  10051. def __str__(self):
  10052. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10053. # end of file