FlatCAMApp.py 548 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093
  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/15"
  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. "tools_cal_toolchange_xy": '',
  782. "tools_cal_sec_point": 'tl',
  783. # Utilities
  784. # file associations
  785. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  786. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  787. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  788. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  789. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  790. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  791. # Keyword list
  792. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  793. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  794. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  795. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  796. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  797. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  798. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  799. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  800. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  801. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  802. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  803. 'z_move',
  804. "script_autocompleter": True,
  805. "script_text": "",
  806. "script_plot": True,
  807. "script_source_file": "",
  808. "document_autocompleter": False,
  809. "document_text": "",
  810. "document_plot": True,
  811. "document_source_file": "",
  812. "document_font_color": '#000000',
  813. "document_sel_color": '#0055ff',
  814. "document_font_size": 6,
  815. "document_tab_size": 80,
  816. })
  817. # ############################################################
  818. # ############### Load defaults from file ####################
  819. # ############################################################
  820. self.old_defaults_found = False
  821. if user_defaults:
  822. self.load_defaults(filename='current_defaults')
  823. if self.defaults['units'] == 'MM':
  824. self.decimals = int(self.defaults['decimals_metric'])
  825. else:
  826. self.decimals = int(self.defaults['decimals_inch'])
  827. self.current_units = self.defaults['units']
  828. # #############################################################################
  829. # ##################### CREATE MULTIPROCESSING POOL ###########################
  830. # #############################################################################
  831. self.pool = Pool(processes=cpu_count())
  832. # ##########################################################################
  833. # ################## Setting the Splash Screen #############################
  834. # ##########################################################################
  835. splash_settings = QSettings("Open Source", "FlatCAM")
  836. if splash_settings.contains("splash_screen"):
  837. show_splash = splash_settings.value("splash_screen")
  838. else:
  839. splash_settings.setValue('splash_screen', 1)
  840. # This will write the setting to the platform specific storage.
  841. del splash_settings
  842. show_splash = 1
  843. if show_splash and self.cmd_line_headless != 1:
  844. splash_pix = QtGui.QPixmap('share/splash.png')
  845. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  846. # self.splash.setMask(splash_pix.mask())
  847. # move splashscreen to the current monitor
  848. desktop = QtWidgets.QApplication.desktop()
  849. screen = desktop.screenNumber(QtGui.QCursor.pos())
  850. current_screen_center = desktop.availableGeometry(screen).center()
  851. self.splash.move(current_screen_center - self.splash.rect().center())
  852. self.splash.show()
  853. self.splash.showMessage(_("FlatCAM is initializing ..."),
  854. alignment=Qt.AlignBottom | Qt.AlignLeft,
  855. color=QtGui.QColor("gray"))
  856. else:
  857. show_splash = 0
  858. # #############################################################################
  859. # ##################### Initialize GUI ########################################
  860. # #############################################################################
  861. # FlatCAM colors used in plotting
  862. self.FC_light_green = '#BBF268BF'
  863. self.FC_dark_green = '#006E20BF'
  864. self.FC_light_blue = '#a5a5ffbf'
  865. self.FC_dark_blue = '#0000ffbf'
  866. QtCore.QObject.__init__(self)
  867. self.ui = FlatCAMGUI(self)
  868. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  869. if theme_settings.contains("theme"):
  870. theme = theme_settings.value('theme', type=str)
  871. else:
  872. theme = 'white'
  873. if theme == 'white':
  874. self.cursor_color_3D = 'black'
  875. else:
  876. self.cursor_color_3D = 'gray'
  877. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  878. self.ui.final_save.connect(self.final_save)
  879. # restore the toolbar view
  880. self.restore_toolbar_view()
  881. # restore the GUI geometry
  882. self.restore_main_win_geom()
  883. # set FlatCAM units in the Status bar
  884. self.set_screen_units(self.defaults['units'])
  885. # #############################################################################
  886. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  887. # #############################################################################
  888. # when adding entries here read the comments in the method found bellow named:
  889. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  890. self.defaults_form_fields = {
  891. # General App
  892. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  893. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  894. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  895. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  896. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  897. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  898. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  899. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  900. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  901. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  902. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  903. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  904. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  905. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  906. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  907. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  908. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  909. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  910. # General GUI Preferences
  911. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  912. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  913. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  914. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  915. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  916. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  917. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  918. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  919. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  920. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  921. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  922. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  923. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  924. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  925. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  926. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  927. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  928. # General GUI Settings
  929. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  930. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  931. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  932. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  933. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  934. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  935. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  936. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  937. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  938. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  939. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  940. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  941. # Gerber General
  942. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  943. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  944. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  945. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  946. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  947. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  948. # Gerber Options
  949. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  950. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  951. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  952. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  953. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  954. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  955. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  956. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  957. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  958. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  959. # Gerber Advanced Options
  960. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  961. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  962. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  963. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  964. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  965. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  966. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  967. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  968. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  969. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  970. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  971. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  972. # Gerber Export
  973. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  974. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  975. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  976. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  977. # Gerber Editor
  978. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  979. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  980. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  981. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  982. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  983. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  984. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  985. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  986. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  987. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  988. "gerber_editor_circ_angle":
  989. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  990. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  991. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  992. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  993. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  994. # Excellon General
  995. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  996. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  997. "excellon_format_upper_in":
  998. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  999. "excellon_format_lower_in":
  1000. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  1001. "excellon_format_upper_mm":
  1002. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1003. "excellon_format_lower_mm":
  1004. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1005. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1006. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1007. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1008. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1009. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1010. # Excellon Options
  1011. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1012. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1013. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1014. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1015. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1016. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1017. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1018. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1019. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1020. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1021. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1022. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1023. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1024. # Excellon Advanced Options
  1025. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1026. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1027. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1028. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1029. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1030. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1031. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1032. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1033. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1034. # Excellon Export
  1035. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1036. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1037. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1038. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1039. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1040. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1041. # Excellon Editor
  1042. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1043. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1044. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1045. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1046. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1047. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1048. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1049. "excellon_editor_circ_angle":
  1050. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1051. # Excellon Slots
  1052. "excellon_editor_slot_direction":
  1053. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1054. "excellon_editor_slot_angle":
  1055. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1056. "excellon_editor_slot_length":
  1057. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1058. # Excellon Slots
  1059. "excellon_editor_slot_array_size":
  1060. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1061. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1062. "excellon_editor_slot_lin_pitch":
  1063. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1064. "excellon_editor_slot_lin_angle":
  1065. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1066. "excellon_editor_slot_circ_dir":
  1067. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1068. "excellon_editor_slot_circ_angle":
  1069. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1070. # Geometry General
  1071. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1072. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1073. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1074. # Geometry Options
  1075. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1076. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1077. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1078. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1079. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1080. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1081. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1082. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1083. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1084. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1085. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1086. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1087. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1088. # Geometry Advanced Options
  1089. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1090. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1091. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1092. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1093. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1094. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1095. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1096. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1097. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1098. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1099. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1100. # Geometry Editor
  1101. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1102. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1103. # CNCJob General
  1104. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1105. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1106. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1107. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1108. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1109. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1110. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1111. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1112. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1113. # CNC Job Options
  1114. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1115. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1116. # CNC Job Advanced Options
  1117. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1118. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1119. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1120. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1121. # NCC Tool
  1122. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1123. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1124. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1125. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1126. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1127. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1128. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1129. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1130. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1131. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1132. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1133. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1134. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1135. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1136. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1137. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1138. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1139. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1140. # CutOut Tool
  1141. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1142. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1143. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1144. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1145. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1146. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1147. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1148. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1149. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1150. # Paint Area Tool
  1151. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1152. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1153. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1154. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1155. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1156. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1157. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1158. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1159. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1160. # 2-sided Tool
  1161. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1162. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1163. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1164. # Film Tool
  1165. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1166. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1167. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1168. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1169. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1170. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1171. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1172. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1173. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1174. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1175. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1176. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1177. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1178. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1179. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1180. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1181. # Panelize Tool
  1182. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1183. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1184. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1185. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1186. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1187. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1188. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1189. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1190. # Calculators Tool
  1191. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1192. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1193. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1194. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1195. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1196. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1197. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1198. # Transformations Tool
  1199. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1200. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1201. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1202. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1203. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1204. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1205. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1206. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1207. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1208. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1209. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1210. # SolderPaste Dispensing Tool
  1211. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1212. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1213. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1214. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1215. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1216. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1217. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1218. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1219. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1220. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1221. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1222. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1223. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1224. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1225. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1226. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1227. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1228. # ###################################################################################
  1229. # ################################ TOOLS 2 ##########################################
  1230. # ###################################################################################
  1231. # Optimal Tool
  1232. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1233. # Check Rules Tool
  1234. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1235. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1236. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1237. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1238. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1239. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1240. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1241. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1242. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1243. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1244. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1245. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1246. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1247. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1248. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1249. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1250. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1251. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1252. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1253. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1254. # QRCode Tool
  1255. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1256. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1257. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1258. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1259. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1260. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1261. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1262. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1263. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1264. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1265. # Copper Thieving Tool
  1266. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1267. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1268. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1269. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1270. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1271. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1272. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1273. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1274. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1275. "tools_copper_thieving_squares_spacing":
  1276. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1277. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1278. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1279. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1280. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1281. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1282. # Fiducials Tool
  1283. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1284. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1285. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1286. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1287. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1288. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1289. # Calibration Tool
  1290. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1291. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1292. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1293. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1294. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1295. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  1296. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  1297. # Utilities
  1298. # File associations
  1299. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1300. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1301. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1302. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1303. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1304. }
  1305. # update the Preferences GUI elements with the values in the self.defaults
  1306. self.defaults_write_form()
  1307. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1308. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1309. # #############################################################################
  1310. # ############################## Data #########################################
  1311. # #############################################################################
  1312. self.recent = []
  1313. self.recent_projects = []
  1314. self.clipboard = QtWidgets.QApplication.clipboard()
  1315. self.project_filename = None
  1316. self.toggle_units_ignore = False
  1317. # #############################################################################
  1318. # ########################## LOAD POSTPROCESSORS ##############################
  1319. # #############################################################################
  1320. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1321. # the preprocessor file
  1322. self.preprocessors = load_preprocessors(self)
  1323. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1324. if 'default' in self.preprocessors.keys():
  1325. new_ppp_dict = dict()
  1326. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1327. default_pp = self.preprocessors.pop('default')
  1328. new_ppp_dict['default'] = default_pp
  1329. # then add the rest of the keys
  1330. for name, val_class in self.preprocessors.items():
  1331. new_ppp_dict[name] = val_class
  1332. # and now put back the ordered dict with 'default' key first
  1333. self.preprocessors = new_ppp_dict
  1334. for name in list(self.preprocessors.keys()):
  1335. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1336. if name.partition('_')[0] == 'Paste':
  1337. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1338. continue
  1339. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1340. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1341. if name == 'hpgl':
  1342. continue
  1343. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1344. # #############################################################################
  1345. # ########################## LOAD LANGUAGES ##################################
  1346. # #############################################################################
  1347. self.languages = fcTranslate.load_languages()
  1348. for name in sorted(self.languages.values()):
  1349. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1350. # #############################################################################
  1351. # ############################ APPLY APP LANGUAGE #############################
  1352. # #############################################################################
  1353. ret_val = fcTranslate.apply_language('strings')
  1354. if ret_val == "no language":
  1355. self.inform.emit('[ERROR] %s' %
  1356. _("Could not find the Language files. The App strings are missing."))
  1357. log.debug("Could not find the Language files. The App strings are missing.")
  1358. else:
  1359. # make the current language the current selection on the language combobox
  1360. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1361. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1362. # #############################################################################
  1363. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1364. # #############################################################################
  1365. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1366. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1367. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1368. self.save_defaults(silent=True, first_time=True)
  1369. self.propagate_defaults(silent=True)
  1370. # def auto_save_defaults():
  1371. # try:
  1372. # self.save_defaults(silent=True)
  1373. # self.propagate_defaults(silent=True)
  1374. # finally:
  1375. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1376. # the following lines activates automatic defaults save
  1377. # if user_defaults:
  1378. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1379. # #############################################################################
  1380. # ########################### UPDATE THE OPTIONS ##############################
  1381. # #############################################################################
  1382. self.options = LoudDict()
  1383. # ----------------------------------------------------------------------------------------------------
  1384. # Update the self.options from the self.defaults
  1385. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1386. # -----------------------------------------------------------------------------------------------------
  1387. # Copy app defaults to project options
  1388. for def_key, def_val in self.defaults.items():
  1389. self.options[def_key] = deepcopy(def_val)
  1390. # self.options.update(self.defaults)
  1391. self.gen_form = None
  1392. self.ger_form = None
  1393. self.exc_form = None
  1394. self.geo_form = None
  1395. self.cnc_form = None
  1396. self.tools_form = None
  1397. self.tools2_form = None
  1398. self.fa_form = None
  1399. # Will show the Preferences GUI
  1400. self.show_preferences_gui()
  1401. # Initialize the color box's color in Preferences -> Global -> Color
  1402. self.init_color_pickers_in_preferences_gui()
  1403. # ### End of Data ####
  1404. # #############################################################################
  1405. # ######################## SETUP OBJECT COLLECTION ############################
  1406. # #############################################################################
  1407. self.collection = ObjectCollection(self)
  1408. self.ui.project_tab_layout.addWidget(self.collection.view)
  1409. # ### Adjust tabs width ## ##
  1410. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1411. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1412. self.collection.view.setMinimumWidth(290)
  1413. self.log.debug("Finished creating Object Collection.")
  1414. # #############################################################################
  1415. # ############################## SETUP Plot Area ##############################
  1416. # #############################################################################
  1417. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1418. if self.defaults["global_graphic_engine"] == '3D':
  1419. self.is_legacy = False
  1420. else:
  1421. self.is_legacy = True
  1422. # Event signals disconnect id holders
  1423. self.mp = None
  1424. self.mm = None
  1425. self.mr = None
  1426. self.mdc = None
  1427. self.mp_zc = None
  1428. # Matplotlib axis
  1429. self.axes = None
  1430. if show_splash:
  1431. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1432. "Canvas initialization started."),
  1433. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1434. color=QtGui.QColor("gray"))
  1435. start_plot_time = time.time() # debug
  1436. self.plotcanvas = None
  1437. self.app_cursor = None
  1438. self.hover_shapes = None
  1439. # setup the PlotCanvas
  1440. self.on_plotcanvas_setup()
  1441. end_plot_time = time.time()
  1442. self.used_time = end_plot_time - start_plot_time
  1443. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1444. if show_splash:
  1445. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1446. "Canvas initialization started.\n"
  1447. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1448. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1449. color=QtGui.QColor("gray"))
  1450. self.ui.splitter.setStretchFactor(1, 2)
  1451. # #############################################################################
  1452. # ################################### SYS TRAY ################################
  1453. # #############################################################################
  1454. if self.defaults["global_systray_icon"]:
  1455. self.parent_w = QtWidgets.QWidget()
  1456. if self.cmd_line_headless == 1:
  1457. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1458. headless=True,
  1459. parent=self.parent_w)
  1460. else:
  1461. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1462. parent=self.parent_w)
  1463. # #############################################################################
  1464. # ################################## Worker SETUP #############################
  1465. # #############################################################################
  1466. if self.defaults["global_worker_number"]:
  1467. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1468. else:
  1469. self.workers = WorkerStack(workers_number=2)
  1470. self.worker_task.connect(self.workers.add_task)
  1471. self.log.debug("Finished creating Workers crew.")
  1472. # #############################################################################
  1473. # ################################# Activity Monitor ##########################
  1474. # #############################################################################
  1475. self.activity_view = FlatCAMActivityView(app=self)
  1476. self.ui.infobar.addWidget(self.activity_view)
  1477. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1478. # #############################################################################
  1479. # ################################## Signal handling ##########################
  1480. # #############################################################################
  1481. # ################################# Custom signals ###########################
  1482. # signal for displaying messages in status bar
  1483. self.inform.connect(self.info)
  1484. # signal to be called when the app is quiting
  1485. self.app_quit.connect(self.quit_application)
  1486. self.message.connect(self.message_dialog)
  1487. self.progress.connect(self.set_progress_bar)
  1488. # signals that are emitted when object state changes
  1489. self.object_created.connect(self.on_object_created)
  1490. self.object_changed.connect(self.on_object_changed)
  1491. self.object_plotted.connect(self.on_object_plotted)
  1492. self.plots_updated.connect(self.on_plots_updated)
  1493. # signals emitted when file state change
  1494. self.file_opened.connect(self.register_recent)
  1495. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1496. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1497. # ############# Standard signals ###################
  1498. # ### Menu
  1499. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1500. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1501. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1502. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1503. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1504. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1505. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1506. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1507. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1508. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1509. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1510. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1511. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1512. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1513. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1514. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1515. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1516. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1517. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1518. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1519. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1520. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1521. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1522. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1523. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1524. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1525. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1526. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1527. self.ui.menufile_exit.triggered.connect(self.final_save)
  1528. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1529. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1530. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1531. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1532. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1533. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1534. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1535. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1536. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1537. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1538. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1539. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1540. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1541. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1542. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1543. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1544. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1545. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1546. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1547. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1548. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1549. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1550. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1551. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1552. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1553. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1554. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1555. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1556. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1557. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1558. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1559. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1560. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1561. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1562. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1563. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1564. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1565. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1566. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1567. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1568. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1569. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1570. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1571. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1572. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1573. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1574. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1575. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1576. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1577. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1578. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1579. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1580. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1581. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1582. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1583. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1584. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1585. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1586. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1587. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1588. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1589. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1590. # ToolBar signals
  1591. self.connect_toolbar_signals()
  1592. # Notebook and Plot Tab Area signals
  1593. # make the right click on the notebook tab and plot tab area tab raise a menu
  1594. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1595. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1596. self.on_tab_setup_context_menu()
  1597. # activate initial state
  1598. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1599. # Context Menu
  1600. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1601. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1602. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1603. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1604. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1605. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1606. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1607. self.ui.clearplot.triggered.connect(self.clear_plots)
  1608. self.ui.replot.triggered.connect(self.plot_all)
  1609. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1610. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1611. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1612. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1613. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1614. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1615. # Preferences Plot Area TAB
  1616. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1617. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1618. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1619. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1620. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1621. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1622. # #############################################################################
  1623. # ######################### GUI PREFERENCES SIGNALS ###########################
  1624. # #############################################################################
  1625. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1626. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1627. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1628. )
  1629. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1630. lambda: self.on_toggle_units(no_pref=False))
  1631. # #############################################################################
  1632. # ############################# GUI COLORS SIGNALS ############################
  1633. # #############################################################################
  1634. # Setting plot colors signals
  1635. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1636. self.on_pf_color_entry)
  1637. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1638. self.on_pf_color_button)
  1639. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1640. self.on_pf_color_spinner)
  1641. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1642. self.on_pf_color_slider)
  1643. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1644. self.on_pl_color_entry)
  1645. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1646. self.on_pl_color_button)
  1647. # Setting selection (left - right) colors signals
  1648. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1649. self.on_sf_color_entry)
  1650. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1651. self.on_sf_color_button)
  1652. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1653. self.on_sf_color_spinner)
  1654. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1655. self.on_sf_color_slider)
  1656. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1657. self.on_sl_color_entry)
  1658. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1659. self.on_sl_color_button)
  1660. # Setting selection (right - left) colors signals
  1661. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1662. self.on_alt_sf_color_entry)
  1663. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1664. self.on_alt_sf_color_button)
  1665. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1666. self.on_alt_sf_color_spinner)
  1667. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1668. self.on_alt_sf_color_slider)
  1669. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1670. self.on_alt_sl_color_entry)
  1671. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1672. self.on_alt_sl_color_button)
  1673. # Setting Editor Draw colors signals
  1674. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1675. self.on_draw_color_entry)
  1676. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1677. self.on_draw_color_button)
  1678. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1679. self.on_sel_draw_color_entry)
  1680. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1681. self.on_sel_draw_color_button)
  1682. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1683. self.on_proj_color_entry)
  1684. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1685. self.on_proj_color_button)
  1686. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1687. self.on_proj_color_dis_entry)
  1688. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1689. self.on_proj_color_dis_button)
  1690. # ############################# workspace setting signals #####################
  1691. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1692. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1693. self.on_workspace_modified
  1694. )
  1695. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1696. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1697. # #############################################################################
  1698. # ############################# GUI SETTINGS SIGNALS ##########################
  1699. # #############################################################################
  1700. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1701. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1702. # ########## CNC Job related signals #############
  1703. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1704. self.on_cnc_custom_parameters)
  1705. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1706. self.on_annotation_fontcolor_entry)
  1707. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1708. self.on_annotation_fontcolor_button)
  1709. # ########## Tools related signals #############
  1710. # Film Tool
  1711. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1712. self.on_film_color_entry)
  1713. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1714. self.on_film_color_button)
  1715. # QRCode Tool
  1716. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1717. self.on_qrcode_fill_color_entry)
  1718. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1719. self.on_qrcode_fill_color_button)
  1720. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1721. self.on_qrcode_back_color_entry)
  1722. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1723. self.on_qrcode_back_color_button)
  1724. # portability changed signal
  1725. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1726. # Object list
  1727. self.collection.view.activated.connect(self.on_row_activated)
  1728. self.collection.item_selected.connect(self.on_row_selected)
  1729. self.object_status_changed.connect(self.on_collection_updated)
  1730. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1731. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1732. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1733. # Export Excellon parameters.
  1734. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1735. self.on_update_exc_export
  1736. )
  1737. # call it once to make sure it is updated at startup
  1738. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1739. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1740. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1741. self.on_excellon_defaults_button)
  1742. # when there are arguments at application startup this get launched
  1743. self.args_at_startup[list].connect(self.on_startup_args)
  1744. # #############################################################################
  1745. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1746. # #############################################################################
  1747. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1748. lambda: self.restore_extensions(ext_type='excellon'))
  1749. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1750. lambda: self.restore_extensions(ext_type='gcode'))
  1751. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1752. lambda: self.restore_extensions(ext_type='gerber'))
  1753. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1754. lambda: self.delete_all_extensions(ext_type='excellon'))
  1755. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1756. lambda: self.delete_all_extensions(ext_type='gcode'))
  1757. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1758. lambda: self.delete_all_extensions(ext_type='gerber'))
  1759. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1760. lambda: self.add_extension(ext_type='excellon'))
  1761. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1762. lambda: self.add_extension(ext_type='gcode'))
  1763. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1764. lambda: self.add_extension(ext_type='gerber'))
  1765. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1766. lambda: self.del_extension(ext_type='excellon'))
  1767. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1768. lambda: self.del_extension(ext_type='gcode'))
  1769. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1770. lambda: self.del_extension(ext_type='gerber'))
  1771. # connect the 'Apply' buttons from the Preferences/File Associations
  1772. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1773. lambda: self.on_register_files(obj_type='excellon'))
  1774. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1775. lambda: self.on_register_files(obj_type='gcode'))
  1776. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1777. lambda: self.on_register_files(obj_type='gerber'))
  1778. # #############################################################################
  1779. # ################################ KEYWORDS SIGNALS ###########################
  1780. # #############################################################################
  1781. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1782. lambda: self.restore_extensions(ext_type='keyword'))
  1783. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1784. lambda: self.delete_all_extensions(ext_type='keyword'))
  1785. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1786. lambda: self.add_extension(ext_type='keyword'))
  1787. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1788. lambda: self.del_extension(ext_type='keyword'))
  1789. # splash screen button signal
  1790. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1791. # connect the abort_all_tasks related slots to the related signals
  1792. self.proc_container.idle_flag.connect(self.app_is_idle)
  1793. # signal emitted when a tab is closed in the Plot Area
  1794. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1795. # #####################################################################################
  1796. # ########### FINISHED CONNECTING SIGNALS #############################################
  1797. # #####################################################################################
  1798. self.log.debug("Finished connecting Signals.")
  1799. # #####################################################################################
  1800. # ########################## Other setups #############################################
  1801. # #####################################################################################
  1802. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1803. # depending on from where those tools are called different actions can be done
  1804. self.call_source = 'app'
  1805. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1806. self.tool_tab_locked = False
  1807. # decide if to show or hide the Notebook side of the screen at startup
  1808. if self.defaults["global_project_at_startup"] is True:
  1809. self.ui.splitter.setSizes([1, 1])
  1810. else:
  1811. self.ui.splitter.setSizes([0, 1])
  1812. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1813. self.setup_obj_classes()
  1814. self.setup_component_editor()
  1815. # #####################################################################################
  1816. # ######################### Auto-complete KEYWORDS ####################################
  1817. # #####################################################################################
  1818. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1819. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1820. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1821. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1822. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1823. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1824. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1825. 'mirror', 'ncc',
  1826. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1827. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1828. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1829. 'save', 'save_project',
  1830. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1831. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1832. 'version', 'write_gcode'
  1833. ]
  1834. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1835. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1836. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1837. 'axisoffset',
  1838. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1839. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1840. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1841. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1842. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1843. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1844. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1845. 'spacing_columns',
  1846. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1847. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1848. ]
  1849. self.tcl_keywords = [
  1850. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1851. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1852. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1853. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1854. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1855. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1856. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1857. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1858. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1859. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1860. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1861. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1862. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1863. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1864. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1865. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1866. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1867. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1868. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1869. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1870. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1871. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1872. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1873. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1874. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1875. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1876. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1877. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1878. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1879. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1880. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1881. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1882. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1883. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1884. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1885. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1886. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1887. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1888. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1889. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1890. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1891. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1892. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1893. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1894. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1895. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1896. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1897. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1898. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1899. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1900. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1901. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1902. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1903. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1904. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1905. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1906. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1907. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1908. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1909. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1910. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1911. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1912. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1913. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1914. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1915. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1916. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1917. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1918. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1919. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1920. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1921. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1922. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1923. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1924. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1925. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1926. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1927. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1928. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1929. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1930. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1931. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1932. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1933. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1934. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1935. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1936. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1937. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1938. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1939. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1940. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1941. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1942. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1943. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1944. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1945. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1946. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1947. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1948. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1949. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1950. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1951. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1952. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1953. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1954. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1955. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1956. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1957. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1958. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1959. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1960. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1961. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1962. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1963. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1964. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1965. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1966. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1967. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1968. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1969. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1970. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1971. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1972. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1973. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1974. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1975. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1976. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1977. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1978. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1979. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1980. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1981. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1982. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1983. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1984. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1985. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1986. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1987. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1988. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1989. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1990. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1991. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1992. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1993. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1994. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1995. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1996. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1997. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1998. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1999. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2000. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2001. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2002. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2003. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2004. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2005. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2006. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2007. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2008. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2009. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2010. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2011. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2012. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2013. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2014. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2015. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2016. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2017. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2018. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2019. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2020. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2021. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2022. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2023. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2024. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2025. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2026. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2027. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2028. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2029. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2030. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2031. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2032. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2033. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2034. ]
  2035. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2036. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2037. # ####################################################################################
  2038. # ####################### Shell SETUP ################################################
  2039. # ####################################################################################
  2040. # this will hold the TCL instance
  2041. self.tcl = None
  2042. self.init_tcl()
  2043. self.shell = FCShell(self, version=self.version)
  2044. self.shell._edit.set_model_data(self.myKeywords)
  2045. self.shell.setWindowIcon(self.ui.app_icon)
  2046. self.shell.setWindowTitle("FlatCAM Shell")
  2047. self.shell.resize(*self.defaults["global_shell_shape"])
  2048. self.shell.append_output("FlatCAM %s - " % self.version)
  2049. self.shell.append_output(_("Type >help< to get started\n\n"))
  2050. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2051. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2052. self.ui.shell_dock.setWidget(self.shell)
  2053. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2054. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2055. QtWidgets.QDockWidget.DockWidgetFloatable |
  2056. QtWidgets.QDockWidget.DockWidgetClosable)
  2057. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2058. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2059. if self.defaults["global_shell_at_startup"]:
  2060. self.ui.shell_dock.show()
  2061. else:
  2062. self.ui.shell_dock.hide()
  2063. # ##################################################################################
  2064. # ###################### Tools and Plugins #########################################
  2065. # ##################################################################################
  2066. self.dblsidedtool = None
  2067. self.distance_tool = None
  2068. self.distance_min_tool = None
  2069. self.panelize_tool = None
  2070. self.film_tool = None
  2071. self.paste_tool = None
  2072. self.calculator_tool = None
  2073. self.rules_tool = None
  2074. self.sub_tool = None
  2075. self.move_tool = None
  2076. self.cutout_tool = None
  2077. self.ncclear_tool = None
  2078. self.optimal_tool = None
  2079. self.paint_tool = None
  2080. self.transform_tool = None
  2081. self.properties_tool = None
  2082. self.pdf_tool = None
  2083. self.image_tool = None
  2084. self.pcb_wizard_tool = None
  2085. self.cal_exc_tool = None
  2086. self.qrcode_tool = None
  2087. self.copper_thieving_tool = None
  2088. self.fiducial_tool = None
  2089. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2090. self.install_tools()
  2091. # ##################################################################################
  2092. # ########################### SETUP RECENT ITEMS ###################################
  2093. # ##################################################################################
  2094. self.setup_recent_items()
  2095. # ##################################################################################
  2096. # ########################### BookMarks Manager ####################################
  2097. # ##################################################################################
  2098. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2099. self.install_bookmarks()
  2100. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2101. # ##################################################################################
  2102. # ############################## Tools Database ####################################
  2103. # ##################################################################################
  2104. self.tools_db_tab = None
  2105. # ### System Font Parsing ###
  2106. # self.f_parse = ParseFont(self)
  2107. # self.parse_system_fonts()
  2108. # #####################################################################################
  2109. # ######################## Check for updates ##########################################
  2110. # #####################################################################################
  2111. # Separate thread (Not worker)
  2112. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2113. if (self.beta is False or self.beta is None) and \
  2114. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2115. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2116. self.thr2 = QtCore.QThread()
  2117. self.worker_task.emit({'fcn': self.version_check,
  2118. 'params': []})
  2119. self.thr2.start(QtCore.QThread.LowPriority)
  2120. # #####################################################################################
  2121. # ######################### Register files with FlatCAM; #############################
  2122. # ######################### It works only for Windows for now ########################
  2123. # #####################################################################################
  2124. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2125. self.on_register_files()
  2126. # #####################################################################################
  2127. # ###################### Variables for global usage ###################################
  2128. # #####################################################################################
  2129. # hold the App units
  2130. self.units = 'MM'
  2131. # coordinates for relative position display
  2132. self.rel_point1 = (0, 0)
  2133. self.rel_point2 = (0, 0)
  2134. # variable to store coordinates
  2135. self.pos = (0, 0)
  2136. self.pos_canvas = (0, 0)
  2137. self.pos_jump = (0, 0)
  2138. # variable to store mouse coordinates
  2139. self.mouse = [0, 0]
  2140. # decide if we have a double click or single click
  2141. self.doubleclick = False
  2142. # store here the is_dragging value
  2143. self.event_is_dragging = False
  2144. # variable to store if a command is active (then the var is not None) and which one it is
  2145. self.command_active = None
  2146. # variable to store the status of moving selection action
  2147. # None value means that it's not an selection action
  2148. # True value = a selection from left to right
  2149. # False value = a selection from right to left
  2150. self.selection_type = None
  2151. # List to store the objects that are currently loaded in FlatCAM
  2152. # This list is updated on each object creation or object delete
  2153. self.all_objects_list = list()
  2154. # List to store the objects that are selected
  2155. self.sel_objects_list = list()
  2156. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2157. self.key_modifiers = None
  2158. # Variable to hold the status of the axis
  2159. self.toggle_axis = True
  2160. # Variable to hold the status of the grid lines
  2161. self.toggle_grid_lines = True
  2162. # Variable to store the status of the fullscreen event
  2163. self.toggle_fscreen = False
  2164. # Variable to store the status of the code editor
  2165. self.toggle_codeeditor = False
  2166. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2167. self.click_noproject = False
  2168. self.cursor = None
  2169. # Variable to store the GCODE that was edited
  2170. self.gcode_edited = ""
  2171. self.text_editor_tab = None
  2172. # reference for the self.ui.code_editor
  2173. self.reference_code_editor = None
  2174. self.script_code = ''
  2175. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2176. self.preferences_changed_flag = False
  2177. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2178. self.tools_db_changed_flag = False
  2179. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2180. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2181. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2182. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2183. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2184. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2185. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2186. 'sbp', 'tap', 'xpi']
  2187. self.svg_list = ['svg']
  2188. self.dxf_list = ['dxf']
  2189. self.pdf_list = ['pdf']
  2190. self.prj_list = ['flatprj']
  2191. self.conf_list = ['flatconfig']
  2192. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2193. # flag for polygons not cleared
  2194. self.poly_not_cleared = False
  2195. # VisPy visuals
  2196. self.isHovering = False
  2197. self.notHovering = True
  2198. # Window geometry
  2199. self.x_pos = None
  2200. self.y_pos = None
  2201. self.width = None
  2202. self.height = None
  2203. # when True, the app has to return from any thread
  2204. self.abort_flag = False
  2205. # set the value used in the Windows Title
  2206. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2207. # this holds a widget that is installed in the Plot Area when View Source option is used
  2208. self.source_editor_tab = None
  2209. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2210. # VisPy visuals
  2211. if self.is_legacy is False:
  2212. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2213. else:
  2214. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2215. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2216. # ###############################################################################
  2217. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2218. # ############# It's done only once after install ###############
  2219. # ###############################################################################
  2220. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2221. fac_def_from_file = factory_file.read()
  2222. factory_defaults = json.loads(fac_def_from_file)
  2223. # if the file contain an empty dictionary then save the factory defaults into the file
  2224. if not factory_defaults:
  2225. self.save_factory_defaults(silent_message=False)
  2226. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2227. initial_lay = 'compact'
  2228. self.on_layout(lay=initial_lay)
  2229. # Set the combobox in Preferences to the current layout
  2230. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2231. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2232. factory_file.close()
  2233. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2234. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2235. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2236. # after the first run, this object should be False
  2237. self.defaults["first_run"] = False
  2238. # ###############################################################################
  2239. # ################# ADDING FlatCAM EDITORS section ##############################
  2240. # ###############################################################################
  2241. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2242. # at the first launch of the App , the editors will not be functional.
  2243. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2244. self.exc_editor = FlatCAMExcEditor(self)
  2245. self.grb_editor = FlatCAMGrbEditor(self)
  2246. self.log.debug("Finished adding FlatCAM Editor's.")
  2247. self.set_ui_title(name=_("New Project - Not saved"))
  2248. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2249. current_platform = platform.architecture()[0]
  2250. if current_platform != '64bit':
  2251. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2252. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2253. # ###############################################################################
  2254. # ####################### Finished the CONSTRUCTOR ##############################
  2255. # ###############################################################################
  2256. App.log.debug("END of constructor. Releasing control.")
  2257. # #####################################################################################
  2258. # ########################## SHOW GUI #################################################
  2259. # #####################################################################################
  2260. # if the app is not started as headless, show it
  2261. if self.cmd_line_headless != 1:
  2262. if show_splash:
  2263. # finish the splash
  2264. self.splash.finish(self.ui)
  2265. mgui_settings = QSettings("Open Source", "FlatCAM")
  2266. if mgui_settings.contains("maximized_gui"):
  2267. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2268. if maximized_ui is True:
  2269. self.ui.showMaximized()
  2270. else:
  2271. self.ui.show()
  2272. else:
  2273. self.ui.show()
  2274. if self.defaults["global_systray_icon"]:
  2275. self.trayIcon.show()
  2276. else:
  2277. log.warning("******************* RUNNING HEADLESS *******************")
  2278. # #####################################################################################
  2279. # ########################## START-UP ARGUMENTS #######################################
  2280. # #####################################################################################
  2281. # test if the program was started with a script as parameter
  2282. if self.cmd_line_shellvar:
  2283. try:
  2284. cnt = 0
  2285. command_tcl = 0
  2286. for i in self.cmd_line_shellvar.split(','):
  2287. if i is not None:
  2288. # noinspection PyBroadException
  2289. try:
  2290. command_tcl = eval(i)
  2291. except Exception:
  2292. command_tcl = i
  2293. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2294. cnt += 1
  2295. # if there are Windows paths then replace the path separator with a Unix like one
  2296. if sys.platform == 'win32':
  2297. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2298. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2299. except Exception as ext:
  2300. print("ERROR: ", ext)
  2301. sys.exit(2)
  2302. if self.cmd_line_shellfile:
  2303. try:
  2304. if self.ui.shell_dock.isHidden():
  2305. self.ui.shell_dock.show()
  2306. with open(self.cmd_line_shellfile, "r") as myfile:
  2307. if show_splash:
  2308. self.splash.showMessage('%s: %ssec\n%s' % (
  2309. _("Canvas initialization started.\n"
  2310. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2311. _("Executing Tcl Script ...")),
  2312. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2313. color=QtGui.QColor("gray"))
  2314. cmd_line_shellfile_text = myfile.read()
  2315. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2316. except Exception as ext:
  2317. print("ERROR: ", ext)
  2318. sys.exit(2)
  2319. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2320. # the path/file_name must be enclosed in quotes if it contain spaces
  2321. if App.args:
  2322. self.args_at_startup.emit(App.args)
  2323. if self.old_defaults_found is True:
  2324. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2325. "Please reboot the application to update."))
  2326. self.old_defaults_found = False
  2327. @staticmethod
  2328. def copy_and_overwrite(from_path, to_path):
  2329. """
  2330. From here:
  2331. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2332. :param from_path: source path
  2333. :param to_path: destination path
  2334. :return: None
  2335. """
  2336. if os.path.exists(to_path):
  2337. shutil.rmtree(to_path)
  2338. try:
  2339. shutil.copytree(from_path, to_path)
  2340. except FileNotFoundError:
  2341. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2342. shutil.copytree(from_new_path, to_path)
  2343. def on_startup_args(self, args, silent=False):
  2344. """
  2345. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2346. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2347. :param args: a list containing the application args at startup
  2348. :return: None
  2349. """
  2350. if args is not None:
  2351. args_to_process = args
  2352. else:
  2353. args_to_process = App.args
  2354. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2355. for argument in args_to_process:
  2356. if '.FlatPrj'.lower() in argument.lower():
  2357. try:
  2358. project_name = str(argument)
  2359. if project_name == "":
  2360. if silent is False:
  2361. self.inform.emit(_("Open cancelled."))
  2362. else:
  2363. # self.open_project(project_name)
  2364. run_from_arg = True
  2365. # self.worker_task.emit({'fcn': self.open_project,
  2366. # 'params': [project_name, run_from_arg]})
  2367. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2368. except Exception as e:
  2369. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2370. elif '.FlatConfig'.lower() in argument.lower():
  2371. try:
  2372. file_name = str(argument)
  2373. if file_name == "":
  2374. if silent is False:
  2375. self.inform.emit(_("Open Config file failed."))
  2376. else:
  2377. run_from_arg = True
  2378. # self.worker_task.emit({'fcn': self.open_config_file,
  2379. # 'params': [file_name, run_from_arg]})
  2380. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2381. except Exception as e:
  2382. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2383. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2384. try:
  2385. file_name = str(argument)
  2386. if file_name == "":
  2387. if silent is False:
  2388. self.inform.emit(_("Open Script file failed."))
  2389. else:
  2390. if silent is False:
  2391. self.on_fileopenscript(name=file_name)
  2392. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2393. self.on_filerunscript(name=file_name)
  2394. except Exception as e:
  2395. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2396. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2397. log.debug("App.on_startup_args() --> Quit event.")
  2398. sys.exit()
  2399. elif 'save'.lower() in argument.lower():
  2400. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2401. self.save_defaults()
  2402. else:
  2403. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2404. proc_arg = argument.lower()
  2405. for ext in exc_list:
  2406. proc_ext = ext.replace(' ', '')
  2407. proc_ext = '.%s' % proc_ext
  2408. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2409. file_name = str(argument)
  2410. if file_name == "":
  2411. if silent is False:
  2412. self.inform.emit(_("Open Excellon file failed."))
  2413. else:
  2414. self.on_fileopenexcellon(name=file_name)
  2415. return
  2416. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2417. for ext in gco_list:
  2418. proc_ext = ext.replace(' ', '')
  2419. proc_ext = '.%s' % proc_ext
  2420. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2421. file_name = str(argument)
  2422. if file_name == "":
  2423. if silent is False:
  2424. self.inform.emit(_("Open GCode file failed."))
  2425. else:
  2426. self.on_fileopengcode(name=file_name)
  2427. return
  2428. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2429. for ext in grb_list:
  2430. proc_ext = ext.replace(' ', '')
  2431. proc_ext = '.%s' % proc_ext
  2432. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2433. file_name = str(argument)
  2434. if file_name == "":
  2435. if silent is False:
  2436. self.inform.emit(_("Open Gerber file failed."))
  2437. else:
  2438. self.on_fileopengerber(name=file_name)
  2439. return
  2440. # if it reached here without already returning then the app was registered with a file that it does not
  2441. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2442. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2443. # for arg in args_to_process:
  2444. # if 'FlatCAM.exe' in arg:
  2445. # continue
  2446. # else:
  2447. # sys.exit(2)
  2448. def set_ui_title(self, name):
  2449. """
  2450. Sets the title of the main window.
  2451. :param name: String that store the project path and project name
  2452. :return: None
  2453. """
  2454. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2455. (self.version,
  2456. ('BETA' if self.beta else ''),
  2457. platform.architecture()[0],
  2458. self.engine,
  2459. name)
  2460. )
  2461. def on_theme_change(self, val):
  2462. t_settings = QSettings("Open Source", "FlatCAM")
  2463. t_settings.setValue('theme', val)
  2464. # This will write the setting to the platform specific storage.
  2465. del t_settings
  2466. self.on_app_restart()
  2467. def on_app_restart(self):
  2468. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2469. # be left in the SySTray
  2470. try:
  2471. self.trayIcon.hide()
  2472. except Exception:
  2473. pass
  2474. fcTranslate.restart_program(app=self)
  2475. def defaults_read_form(self):
  2476. """
  2477. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2478. :return: None
  2479. """
  2480. for option in self.defaults_form_fields:
  2481. try:
  2482. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2483. except Exception as e:
  2484. log.debug("App.defaults_read_form() --> %s" % str(e))
  2485. def defaults_write_form(self, factor=None, fl_units=None):
  2486. """
  2487. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2488. self.defaults dictionary.
  2489. :param factor: will apply a factor to the values that written in the GUI elements
  2490. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2491. :return: None
  2492. """
  2493. for option in self.defaults:
  2494. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2495. # try:
  2496. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2497. # except KeyError:
  2498. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2499. # # TODO: Rethink this?
  2500. # pass
  2501. def defaults_write_form_field(self, field, factor=None, units=None):
  2502. """
  2503. Basically it is the worker in the self.defaults_write_form()
  2504. :param field: the GUI element in Preferences GUI to be updated
  2505. :param factor: factor to be applied to the field parameter
  2506. :param units: current FLatCAM measuring units
  2507. :return: None, it updates GUI elements
  2508. """
  2509. try:
  2510. if factor is None:
  2511. if units is None:
  2512. self.defaults_form_fields[field].set_value(self.defaults[field])
  2513. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2514. self.defaults_form_fields[field].set_value(self.defaults[field])
  2515. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2516. self.defaults_form_fields[field].set_value(self.defaults[field])
  2517. else:
  2518. if units is None:
  2519. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2520. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2521. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2522. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2523. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2524. except KeyError:
  2525. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2526. # TODO: Rethink this?
  2527. pass
  2528. except AttributeError:
  2529. log.debug(field)
  2530. def clear_pool(self):
  2531. """
  2532. Clear the multiprocessing pool and calls garbage collector.
  2533. :return: None
  2534. """
  2535. self.pool.close()
  2536. self.pool = Pool()
  2537. self.pool_recreated.emit(self.pool)
  2538. gc.collect()
  2539. def install_tools(self):
  2540. """
  2541. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2542. Instantiation of the Tools classes.
  2543. The order that the tools are installed is important as they can depend on each other install position.
  2544. :return: None
  2545. """
  2546. self.dblsidedtool = DblSidedTool(self)
  2547. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2548. self.cal_exc_tool = ToolCalibration(self)
  2549. self.cal_exc_tool.install(icon=QtGui.QIcon('share/calibrate_16.png'), pos=self.ui.menutool,
  2550. before=self.dblsidedtool.menuAction,
  2551. separator=False)
  2552. self.distance_tool = Distance(self)
  2553. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2554. before=self.ui.menueditorigin,
  2555. separator=False)
  2556. self.distance_min_tool = DistanceMin(self)
  2557. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2558. before=self.ui.menueditorigin,
  2559. separator=True)
  2560. self.panelize_tool = Panelize(self)
  2561. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2562. self.film_tool = Film(self)
  2563. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2564. self.paste_tool = SolderPaste(self)
  2565. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2566. self.calculator_tool = ToolCalculator(self)
  2567. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2568. self.sub_tool = ToolSub(self)
  2569. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2570. self.rules_tool = RulesCheck(self)
  2571. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2572. self.optimal_tool = ToolOptimal(self)
  2573. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2574. self.move_tool = ToolMove(self)
  2575. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2576. before=self.ui.menueditorigin, separator=True)
  2577. self.cutout_tool = CutOut(self)
  2578. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2579. before=self.sub_tool.menuAction)
  2580. self.ncclear_tool = NonCopperClear(self)
  2581. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2582. before=self.sub_tool.menuAction, separator=True)
  2583. self.paint_tool = ToolPaint(self)
  2584. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2585. before=self.sub_tool.menuAction, separator=True)
  2586. self.copper_thieving_tool = ToolCopperThieving(self)
  2587. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2588. self.fiducial_tool = ToolFiducials(self)
  2589. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2590. self.qrcode_tool = QRCode(self)
  2591. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2592. self.transform_tool = ToolTransform(self)
  2593. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2594. self.properties_tool = Properties(self)
  2595. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2596. self.pdf_tool = ToolPDF(self)
  2597. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2598. separator=True)
  2599. self.image_tool = ToolImage(self)
  2600. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2601. separator=True)
  2602. self.pcb_wizard_tool = PcbWizard(self)
  2603. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2604. self.log.debug("Tools are installed.")
  2605. def remove_tools(self):
  2606. """
  2607. Will remove all the actions in the Tool menu.
  2608. :return: None
  2609. """
  2610. for act in self.ui.menutool.actions():
  2611. self.ui.menutool.removeAction(act)
  2612. def init_tools(self):
  2613. """
  2614. Initialize the Tool tab in the notebook side of the central widget.
  2615. Remove the actions in the Tools menu.
  2616. Instantiate again the FlatCAM tools (plugins).
  2617. All this is required when changing the layout: standard, compact etc.
  2618. :return: None
  2619. """
  2620. log.debug("init_tools()")
  2621. # delete the data currently in the Tools Tab and the Tab itself
  2622. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2623. if widget is not None:
  2624. widget.deleteLater()
  2625. self.ui.notebook.removeTab(2)
  2626. # rebuild the Tools Tab
  2627. self.ui.tool_tab = QtWidgets.QWidget()
  2628. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2629. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2630. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2631. self.ui.tool_scroll_area = VerticalScrollArea()
  2632. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2633. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2634. # first remove all of them
  2635. self.remove_tools()
  2636. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2637. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2638. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2639. # third install all of them
  2640. self.install_tools()
  2641. self.log.debug("Tools are initialized.")
  2642. # def parse_system_fonts(self):
  2643. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2644. # 'params': []})
  2645. def connect_toolbar_signals(self):
  2646. """
  2647. Reconnect the signals to the actions in the toolbar.
  2648. This has to be done each time after the FlatCAM tools are removed/installed.
  2649. :return: None
  2650. """
  2651. # Toolbar
  2652. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2653. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2654. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2655. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2656. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2657. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2658. self.ui.replot_btn.triggered.connect(self.plot_all)
  2659. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2660. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2661. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2662. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2663. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2664. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2665. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2666. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2667. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2668. self.ui.delete_btn.triggered.connect(self.on_delete)
  2669. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2670. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2671. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2672. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2673. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2674. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2675. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2676. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2677. # Tools Toolbar Signals
  2678. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2679. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2680. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2681. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2682. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2683. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2684. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2685. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2686. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2687. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2688. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2689. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2690. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2691. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2692. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2693. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2694. def object2editor(self):
  2695. """
  2696. Send the current Geometry or Excellon object (if any) into the it's editor.
  2697. :return: None
  2698. """
  2699. self.report_usage("object2editor()")
  2700. # disable the objects menu as it may interfere with the Editors
  2701. self.ui.menuobjects.setDisabled(True)
  2702. edited_object = self.collection.get_active()
  2703. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2704. isinstance(edited_object, FlatCAMExcellon):
  2705. pass
  2706. else:
  2707. self.inform.emit('[WARNING_NOTCL] %s' %
  2708. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2709. return
  2710. if isinstance(edited_object, FlatCAMGeometry):
  2711. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2712. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2713. # we set the notebook to hidden
  2714. self.ui.splitter.setSizes([0, 1])
  2715. if edited_object.multigeo is True:
  2716. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2717. if len(sel_rows) > 1:
  2718. self.inform.emit('[WARNING_NOTCL] %s' %
  2719. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2720. "is not possible.\n"
  2721. "Edit only one geometry at a time."))
  2722. # determine the tool dia of the selected tool
  2723. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2724. # now find the key in the edited_object.tools that has this tooldia
  2725. multi_tool = 1
  2726. for tool in edited_object.tools:
  2727. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2728. multi_tool = tool
  2729. break
  2730. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2731. else:
  2732. self.geo_editor.edit_fcgeometry(edited_object)
  2733. # set call source to the Editor we go into
  2734. self.call_source = 'geo_editor'
  2735. elif isinstance(edited_object, FlatCAMExcellon):
  2736. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2737. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2738. if self.ui.splitter.sizes()[0] == 0:
  2739. self.ui.splitter.setSizes([1, 1])
  2740. self.exc_editor.edit_fcexcellon(edited_object)
  2741. # set call source to the Editor we go into
  2742. self.call_source = 'exc_editor'
  2743. elif isinstance(edited_object, FlatCAMGerber):
  2744. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2745. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2746. if self.ui.splitter.sizes()[0] == 0:
  2747. self.ui.splitter.setSizes([1, 1])
  2748. self.grb_editor.edit_fcgerber(edited_object)
  2749. # set call source to the Editor we go into
  2750. self.call_source = 'grb_editor'
  2751. # make sure that we can't select another object while in Editor Mode:
  2752. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2753. self.ui.project_frame.setDisabled(True)
  2754. # delete any selection shape that might be active as they are not relevant in Editor
  2755. self.delete_selection_shape()
  2756. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2757. self.ui.plot_tab_area.protectTab(0)
  2758. self.inform.emit('[WARNING_NOTCL] %s' %
  2759. _("Editor is activated ..."))
  2760. self.should_we_save = True
  2761. def editor2object(self, cleanup=None):
  2762. """
  2763. Transfers the Geometry or Excellon from it's editor to the current object.
  2764. :return: None
  2765. """
  2766. self.report_usage("editor2object()")
  2767. # re-enable the objects menu that was disabled on entry in Editor mode
  2768. self.ui.menuobjects.setDisabled(False)
  2769. # do not update a geometry or excellon object unless it comes out of an editor
  2770. if self.call_source != 'app':
  2771. edited_obj = self.collection.get_active()
  2772. if cleanup is None:
  2773. msgbox = QtWidgets.QMessageBox()
  2774. msgbox.setText(_("Do you want to save the edited object?"))
  2775. msgbox.setWindowTitle(_("Close Editor"))
  2776. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2777. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2778. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2779. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2780. msgbox.setDefaultButton(bt_yes)
  2781. msgbox.exec_()
  2782. response = msgbox.clickedButton()
  2783. if response == bt_yes:
  2784. # clean the Tools Tab
  2785. self.ui.tool_scroll_area.takeWidget()
  2786. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2787. self.ui.notebook.setTabText(2, "Tool")
  2788. if isinstance(edited_obj, FlatCAMGeometry):
  2789. obj_type = "Geometry"
  2790. if cleanup is None:
  2791. self.geo_editor.update_fcgeometry(edited_obj)
  2792. self.geo_editor.update_options(edited_obj)
  2793. self.geo_editor.deactivate()
  2794. # update the geo object options so it is including the bounding box values
  2795. try:
  2796. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2797. edited_obj.options['xmin'] = xmin
  2798. edited_obj.options['ymin'] = ymin
  2799. edited_obj.options['xmax'] = xmax
  2800. edited_obj.options['ymax'] = ymax
  2801. except AttributeError as e:
  2802. self.inform.emit('[WARNING] %s' %
  2803. _("Object empty after edit."))
  2804. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2805. elif isinstance(edited_obj, FlatCAMGerber):
  2806. obj_type = "Gerber"
  2807. if cleanup is None:
  2808. self.grb_editor.update_fcgerber()
  2809. self.grb_editor.update_options(edited_obj)
  2810. self.grb_editor.deactivate_grb_editor()
  2811. # delete the old object (the source object) if it was an empty one
  2812. try:
  2813. if len(edited_obj.solid_geometry) == 0:
  2814. old_name = edited_obj.options['name']
  2815. self.collection.set_active(old_name)
  2816. self.collection.delete_active()
  2817. except TypeError:
  2818. # if the solid_geometry is a single Polygon the len() will not work
  2819. # in any case, falling here means that we have something in the solid_geometry, even if only
  2820. # a single Polygon, therefore we pass this
  2821. pass
  2822. # restore GUI to the Selected TAB
  2823. # Remove anything else in the GUI
  2824. self.ui.selected_scroll_area.takeWidget()
  2825. # Switch notebook to Selected page
  2826. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2827. elif isinstance(edited_obj, FlatCAMExcellon):
  2828. obj_type = "Excellon"
  2829. if cleanup is None:
  2830. self.exc_editor.update_fcexcellon(edited_obj)
  2831. self.exc_editor.update_options(edited_obj)
  2832. self.exc_editor.deactivate()
  2833. # delete the old object (the source object) if it was an empty one
  2834. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2835. old_name = edited_obj.options['name']
  2836. self.collection.set_active(old_name)
  2837. self.collection.delete_active()
  2838. # restore GUI to the Selected TAB
  2839. # Remove anything else in the GUI
  2840. self.ui.tool_scroll_area.takeWidget()
  2841. # Switch notebook to Selected page
  2842. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2843. else:
  2844. self.inform.emit('[WARNING_NOTCL] %s' %
  2845. _("Select a Gerber, Geometry or Excellon Object to update."))
  2846. return
  2847. self.inform.emit('[selected] %s %s' %
  2848. (obj_type, _("is updated, returning to App...")))
  2849. elif response == bt_no:
  2850. # clean the Tools Tab
  2851. self.ui.tool_scroll_area.takeWidget()
  2852. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2853. self.ui.notebook.setTabText(2, "Tool")
  2854. if isinstance(edited_obj, FlatCAMGeometry):
  2855. self.geo_editor.deactivate()
  2856. elif isinstance(edited_obj, FlatCAMGerber):
  2857. self.grb_editor.deactivate_grb_editor()
  2858. elif isinstance(edited_obj, FlatCAMExcellon):
  2859. self.exc_editor.deactivate()
  2860. # set focus on the project tab
  2861. else:
  2862. self.inform.emit('[WARNING_NOTCL] %s' %
  2863. _("Select a Gerber, Geometry or Excellon Object to update."))
  2864. return
  2865. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2866. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2867. elif response == bt_cancel:
  2868. return
  2869. else:
  2870. if isinstance(edited_obj, FlatCAMGeometry):
  2871. self.geo_editor.deactivate()
  2872. elif isinstance(edited_obj, FlatCAMGerber):
  2873. self.grb_editor.deactivate_grb_editor()
  2874. elif isinstance(edited_obj, FlatCAMExcellon):
  2875. self.exc_editor.deactivate()
  2876. else:
  2877. self.inform.emit('[WARNING_NOTCL] %s' %
  2878. _("Select a Gerber, Geometry or Excellon Object to update."))
  2879. return
  2880. # if notebook is hidden we show it
  2881. if self.ui.splitter.sizes()[0] == 0:
  2882. self.ui.splitter.setSizes([1, 1])
  2883. # restore the call_source to app
  2884. self.call_source = 'app'
  2885. edited_obj.plot()
  2886. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2887. self.ui.plot_tab_area.protectTab(0)
  2888. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2889. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2890. self.ui.project_frame.setDisabled(False)
  2891. def get_last_folder(self):
  2892. """
  2893. Get the folder path from where the last file was opened.
  2894. :return: String, last opened folder path
  2895. """
  2896. return self.defaults["global_last_folder"]
  2897. def get_last_save_folder(self):
  2898. """
  2899. Get the folder path from where the last file was saved.
  2900. :return: String, last saved folder path
  2901. """
  2902. loc = self.defaults["global_last_save_folder"]
  2903. if loc is None:
  2904. loc = self.defaults["global_last_folder"]
  2905. if loc is None:
  2906. loc = os.path.dirname(__file__)
  2907. return loc
  2908. def report_usage(self, resource):
  2909. """
  2910. Increments usage counter for the given resource
  2911. in self.defaults['global_stats'].
  2912. :param resource: Name of the resource.
  2913. :return: None
  2914. """
  2915. if resource in self.defaults['global_stats']:
  2916. self.defaults['global_stats'][resource] += 1
  2917. else:
  2918. self.defaults['global_stats'][resource] = 1
  2919. def init_tcl(self):
  2920. """
  2921. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2922. :return: None
  2923. """
  2924. if hasattr(self, 'tcl') and self.tcl is not None:
  2925. # self.tcl = None
  2926. # TODO we need to clean non default variables and procedures here
  2927. # new object cannot be used here as it will not remember values created for next passes,
  2928. # because tcl was execudted in old instance of TCL
  2929. pass
  2930. else:
  2931. self.tcl = tk.Tcl()
  2932. self.setup_shell()
  2933. self.log.debug("TCL Shell has been initialized.")
  2934. # TODO: This shouldn't be here.
  2935. class TclErrorException(Exception):
  2936. """
  2937. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2938. """
  2939. pass
  2940. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2941. """
  2942. Shows a message on the FlatCAM Shell
  2943. :param msg: Message to display.
  2944. :param show: Opens the shell.
  2945. :param error: Shows the message as an error.
  2946. :param warning: Shows the message as an warning.
  2947. :param success: Shows the message as an success.
  2948. :param selected: Indicate that something was selected on canvas
  2949. :return: None
  2950. """
  2951. if show:
  2952. self.ui.shell_dock.show()
  2953. try:
  2954. if error:
  2955. self.shell.append_error(msg + "\n")
  2956. elif warning:
  2957. self.shell.append_warning(msg + "\n")
  2958. elif success:
  2959. self.shell.append_success(msg + "\n")
  2960. elif selected:
  2961. self.shell.append_selected(msg + "\n")
  2962. else:
  2963. self.shell.append_output(msg + "\n")
  2964. except AttributeError:
  2965. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2966. def raise_tcl_unknown_error(self, unknownException):
  2967. """
  2968. Raise exception if is different type than TclErrorException
  2969. this is here mainly to show unknown errors inside TCL shell console.
  2970. :param unknownException:
  2971. :return:
  2972. """
  2973. if not isinstance(unknownException, self.TclErrorException):
  2974. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2975. else:
  2976. raise unknownException
  2977. def display_tcl_error(self, error, error_info=None):
  2978. """
  2979. Escape bracket [ with '\' otherwise there is error
  2980. "ERROR: missing close-bracket" instead of real error
  2981. :param error: it may be text or exception
  2982. :param error_info: Some informations about the error
  2983. :return: None
  2984. """
  2985. if isinstance(error, Exception):
  2986. exc_type, exc_value, exc_traceback = error_info
  2987. if not isinstance(error, self.TclErrorException):
  2988. show_trace = 1
  2989. else:
  2990. show_trace = int(self.defaults['global_verbose_error_level'])
  2991. if show_trace > 0:
  2992. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2993. trc_formated = []
  2994. for a in reversed(trc):
  2995. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2996. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2997. else:
  2998. text = "%s" % error
  2999. else:
  3000. text = error
  3001. text = text.replace('[', '\\[').replace('"', '\\"')
  3002. self.tcl.eval('return -code error "%s"' % text)
  3003. def raise_tcl_error(self, text):
  3004. """
  3005. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3006. :param text: text of error
  3007. :return: raise exception
  3008. """
  3009. self.display_tcl_error(text)
  3010. raise self.TclErrorException(text)
  3011. def exec_command(self, text, no_echo=False):
  3012. """
  3013. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3014. Also handles execution in separated threads
  3015. :param text: FlatCAM TclCommand with parameters
  3016. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3017. will create crashes of the _Expandable_Edit widget
  3018. :return: output if there was any
  3019. """
  3020. self.report_usage('exec_command')
  3021. result = self.exec_command_test(text, False, no_echo=no_echo)
  3022. # MS: added this method call so the geometry is updated once the TCL command is executed
  3023. # if no_plot is None:
  3024. # self.plot_all()
  3025. return result
  3026. def exec_command_test(self, text, reraise=True, no_echo=False):
  3027. """
  3028. Same as exec_command(...) with additional control over exceptions.
  3029. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3030. :param text: Input command
  3031. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3032. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3033. will create crashes of the _Expandable_Edit widget
  3034. :return: Output from the command
  3035. """
  3036. tcl_command_string = str(text)
  3037. try:
  3038. if no_echo is False:
  3039. self.shell.open_proccessing() # Disables input box.
  3040. result = self.tcl.eval(str(tcl_command_string))
  3041. if result != 'None' and no_echo is False:
  3042. self.shell.append_output(result + '\n')
  3043. except tk.TclError as e:
  3044. # This will display more precise answer if something in TCL shell fails
  3045. result = self.tcl.eval("set errorInfo")
  3046. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3047. if no_echo is False:
  3048. self.shell.append_error('ERROR: ' + result + '\n')
  3049. # Show error in console and just return or in test raise exception
  3050. if reraise:
  3051. raise e
  3052. finally:
  3053. if no_echo is False:
  3054. self.shell.close_proccessing()
  3055. pass
  3056. return result
  3057. # """
  3058. # Code below is unsused. Saved for later.
  3059. # """
  3060. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3061. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3062. # self.log.debug(parts)
  3063. # try:
  3064. # if parts[0] not in commands:
  3065. # self.shell.append_error("Unknown command\n")
  3066. # return
  3067. #
  3068. # #import inspect
  3069. # #inspect.getargspec(someMethod)
  3070. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3071. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3072. # self.shell.append_error(
  3073. # "Command %s takes %d arguments. %d given.\n" %
  3074. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3075. # )
  3076. # return
  3077. #
  3078. # cmdfcn = commands[parts[0]]["fcn"]
  3079. # cmdconv = commands[parts[0]]["converters"]
  3080. # if len(parts) - 1 > 0:
  3081. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3082. # else:
  3083. # retval = cmdfcn()
  3084. # retfcn = commands[parts[0]]["retfcn"]
  3085. # if retval and retfcn(retval):
  3086. # self.shell.append_output(retfcn(retval) + "\n")
  3087. #
  3088. # except Exception as e:
  3089. # #self.shell.append_error(''.join(traceback.format_exc()))
  3090. # #self.shell.append_error("?\n")
  3091. # self.shell.append_error(str(e) + "\n")
  3092. def info(self, msg):
  3093. """
  3094. Informs the user. Normally on the status bar, optionally
  3095. also on the shell.
  3096. :param msg: Text to write.
  3097. :return: None
  3098. """
  3099. # Type of message in brackets at the beginning of the message.
  3100. match = re.search("\[([^\]]+)\](.*)", msg)
  3101. if match:
  3102. level = match.group(1)
  3103. msg_ = match.group(2)
  3104. self.ui.fcinfo.set_status(str(msg_), level=level)
  3105. if level.lower() == "error":
  3106. self.shell_message(msg, error=True, show=True)
  3107. elif level.lower() == "warning":
  3108. self.shell_message(msg, warning=True, show=True)
  3109. elif level.lower() == "error_notcl":
  3110. self.shell_message(msg, error=True, show=False)
  3111. elif level.lower() == "warning_notcl":
  3112. self.shell_message(msg, warning=True, show=False)
  3113. elif level.lower() == "success":
  3114. self.shell_message(msg, success=True, show=False)
  3115. elif level.lower() == "selected":
  3116. self.shell_message(msg, selected=True, show=False)
  3117. else:
  3118. self.shell_message(msg, show=False)
  3119. else:
  3120. self.ui.fcinfo.set_status(str(msg), level="info")
  3121. # make sure that if the message is to clear the infobar with a space
  3122. # is not printed over and over on the shell
  3123. if msg != '':
  3124. self.shell_message(msg)
  3125. def restore_toolbar_view(self):
  3126. """
  3127. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3128. was saved in the defaults dictionary.
  3129. :return: None
  3130. """
  3131. tb = self.defaults["global_toolbar_view"]
  3132. if tb & 1:
  3133. self.ui.toolbarfile.setVisible(True)
  3134. else:
  3135. self.ui.toolbarfile.setVisible(False)
  3136. if tb & 2:
  3137. self.ui.toolbargeo.setVisible(True)
  3138. else:
  3139. self.ui.toolbargeo.setVisible(False)
  3140. if tb & 4:
  3141. self.ui.toolbarview.setVisible(True)
  3142. else:
  3143. self.ui.toolbarview.setVisible(False)
  3144. if tb & 8:
  3145. self.ui.toolbartools.setVisible(True)
  3146. else:
  3147. self.ui.toolbartools.setVisible(False)
  3148. if tb & 16:
  3149. self.ui.exc_edit_toolbar.setVisible(True)
  3150. else:
  3151. self.ui.exc_edit_toolbar.setVisible(False)
  3152. if tb & 32:
  3153. self.ui.geo_edit_toolbar.setVisible(True)
  3154. else:
  3155. self.ui.geo_edit_toolbar.setVisible(False)
  3156. if tb & 64:
  3157. self.ui.grb_edit_toolbar.setVisible(True)
  3158. else:
  3159. self.ui.grb_edit_toolbar.setVisible(False)
  3160. if tb & 128:
  3161. self.ui.snap_toolbar.setVisible(True)
  3162. else:
  3163. self.ui.snap_toolbar.setVisible(False)
  3164. if tb & 256:
  3165. self.ui.toolbarshell.setVisible(True)
  3166. else:
  3167. self.ui.toolbarshell.setVisible(False)
  3168. def load_defaults(self, filename):
  3169. """
  3170. Loads the aplication's default settings from current_defaults.FlatConfig into
  3171. ``self.defaults``.
  3172. :return: None
  3173. """
  3174. try:
  3175. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3176. options = f.read()
  3177. f.close()
  3178. except IOError:
  3179. self.log.error("Could not load defaults file.")
  3180. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3181. # in case the defaults file can't be loaded, show all toolbars
  3182. self.defaults["global_toolbar_view"] = 511
  3183. return
  3184. try:
  3185. defaults = json.loads(options)
  3186. except Exception:
  3187. # in case the defaults file can't be loaded, show all toolbars
  3188. self.defaults["global_toolbar_view"] = 511
  3189. e = sys.exc_info()[0]
  3190. App.log.error(str(e))
  3191. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3192. return
  3193. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3194. for k, v in defaults.items():
  3195. if k in self.defaults:
  3196. self.defaults[k] = v
  3197. # delete old factory defaults
  3198. try:
  3199. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3200. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3201. os.remove(fact_def_file_path)
  3202. # recreate a new factory defaults file and save the factory defaults data into it
  3203. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3204. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3205. f_f_def_s.close()
  3206. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3207. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3208. except Exception as e:
  3209. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3210. self.old_defaults_found = True
  3211. else:
  3212. self.defaults.update(defaults)
  3213. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3214. def on_import_preferences(self):
  3215. """
  3216. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3217. ``self.defaults``.
  3218. :return: None
  3219. """
  3220. self.report_usage("on_import_preferences")
  3221. App.log.debug("on_import_preferences()")
  3222. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3223. try:
  3224. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3225. directory=self.data_path,
  3226. filter=filter_)
  3227. except TypeError:
  3228. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3229. filter=filter_)
  3230. filename = str(filename)
  3231. if filename == "":
  3232. self.inform.emit('[WARNING_NOTCL] %s' %
  3233. _("FlatCAM preferences import cancelled."))
  3234. else:
  3235. try:
  3236. f = open(filename)
  3237. options = f.read()
  3238. f.close()
  3239. except IOError:
  3240. self.log.error("Could not load defaults file.")
  3241. self.inform.emit('[ERROR_NOTCL] %s' %
  3242. _("Could not load defaults file."))
  3243. return
  3244. try:
  3245. defaults_from_file = json.loads(options)
  3246. except Exception:
  3247. e = sys.exc_info()[0]
  3248. App.log.error(str(e))
  3249. self.inform.emit('[ERROR_NOTCL] %s' %
  3250. _("Failed to parse defaults file."))
  3251. return
  3252. self.defaults.update(defaults_from_file)
  3253. self.on_preferences_edited()
  3254. self.inform.emit('[success] %s: %s' %
  3255. (_("Imported Defaults from"), filename))
  3256. def on_export_preferences(self):
  3257. """
  3258. Save the defaults dictionary to a file.
  3259. :return: None
  3260. """
  3261. self.report_usage("on_export_preferences")
  3262. App.log.debug("on_export_preferences()")
  3263. defaults_file_content = None
  3264. self.date = str(datetime.today()).rpartition('.')[0]
  3265. self.date = ''.join(c for c in self.date if c not in ':-')
  3266. self.date = self.date.replace(' ', '_')
  3267. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3268. try:
  3269. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3270. caption=_("Export FlatCAM Preferences"),
  3271. directory=self.data_path + '/preferences_' + self.date,
  3272. filter=filter__
  3273. )
  3274. except TypeError:
  3275. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3276. filter=filter__)
  3277. filename = str(filename)
  3278. defaults_from_file = {}
  3279. if filename == "":
  3280. self.inform.emit('[WARNING_NOTCL] %s' %
  3281. _("FlatCAM preferences export cancelled."))
  3282. return
  3283. else:
  3284. try:
  3285. f = open(filename, 'w')
  3286. defaults_file_content = f.read()
  3287. f.close()
  3288. except PermissionError:
  3289. self.inform.emit('[WARNING] %s' %
  3290. _("Permission denied, saving not possible.\n"
  3291. "Most likely another app is holding the file open and not accessible."))
  3292. return
  3293. except IOError:
  3294. App.log.debug('Creating a new preferences file ...')
  3295. f = open(filename, 'w')
  3296. json.dump({}, f)
  3297. f.close()
  3298. except Exception:
  3299. e = sys.exc_info()[0]
  3300. App.log.error("Could not load defaults file.")
  3301. App.log.error(str(e))
  3302. self.inform.emit('[ERROR_NOTCL] %s' %
  3303. _("Could not load preferences file."))
  3304. return
  3305. try:
  3306. defaults_from_file = json.loads(defaults_file_content)
  3307. except Exception:
  3308. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3309. # Update options
  3310. self.defaults_read_form()
  3311. defaults_from_file.update(self.defaults)
  3312. self.propagate_defaults(silent=True)
  3313. # Save update options
  3314. try:
  3315. f = open(filename, "w")
  3316. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3317. f.close()
  3318. except Exception:
  3319. self.inform.emit('[ERROR_NOTCL] %s' %
  3320. _("Failed to write defaults to file."))
  3321. return
  3322. if self.defaults["global_open_style"] is False:
  3323. self.file_opened.emit("preferences", filename)
  3324. self.file_saved.emit("preferences", filename)
  3325. self.inform.emit('[success] %s: %s' %
  3326. (_("Exported preferences to"), filename))
  3327. def on_preferences_open_folder(self):
  3328. """
  3329. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3330. :return: None
  3331. """
  3332. self.report_usage("on_preferences_open_folder()")
  3333. if sys.platform == 'win32':
  3334. subprocess.Popen('explorer %s' % self.data_path)
  3335. elif sys.platform == 'darwin':
  3336. os.system('open "%s"' % self.data_path)
  3337. else:
  3338. subprocess.Popen(['xdg-open', self.data_path])
  3339. self.inform.emit('[success] %s' %
  3340. _("FlatCAM Preferences Folder opened."))
  3341. def save_geometry(self, x, y, width, height, notebook_width):
  3342. """
  3343. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3344. launch of the application.
  3345. :param x: X position of the main window
  3346. :param y: Y position of the main window
  3347. :param width: width of the main window
  3348. :param height: height of the main window
  3349. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3350. :return: None
  3351. """
  3352. self.defaults["global_def_win_x"] = x
  3353. self.defaults["global_def_win_y"] = y
  3354. self.defaults["global_def_win_w"] = width
  3355. self.defaults["global_def_win_h"] = height
  3356. self.defaults["global_def_notebook_width"] = notebook_width
  3357. self.save_defaults()
  3358. def restore_main_win_geom(self):
  3359. try:
  3360. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3361. self.defaults["global_def_win_y"],
  3362. self.defaults["global_def_win_w"],
  3363. self.defaults["global_def_win_h"])
  3364. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3365. except KeyError as e:
  3366. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3367. def message_dialog(self, title, message, kind="info"):
  3368. """
  3369. Builds and show a custom QMessageBox to be used in FlatCAM.
  3370. :param title: title of the QMessageBox
  3371. :param message: message to be displayed
  3372. :param kind: type of QMessageBox; will display a specific icon.
  3373. :return:
  3374. """
  3375. icon = {"info": QtWidgets.QMessageBox.Information,
  3376. "warning": QtWidgets.QMessageBox.Warning,
  3377. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3378. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3379. dlg.setText(message)
  3380. dlg.exec_()
  3381. def register_recent(self, kind, filename):
  3382. """
  3383. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3384. dictionary.
  3385. :param kind: type of file that was opened
  3386. :param filename: the path and file name for the file that was opened
  3387. :return:
  3388. """
  3389. self.log.debug("register_recent()")
  3390. self.log.debug(" %s" % kind)
  3391. self.log.debug(" %s" % filename)
  3392. record = {'kind': str(kind), 'filename': str(filename)}
  3393. if record in self.recent:
  3394. return
  3395. if record in self.recent_projects:
  3396. return
  3397. if record['kind'] == 'project':
  3398. self.recent_projects.insert(0, record)
  3399. else:
  3400. self.recent.insert(0, record)
  3401. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3402. self.recent.pop()
  3403. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3404. self.recent_projects.pop()
  3405. try:
  3406. f = open(self.data_path + '/recent.json', 'w')
  3407. except IOError:
  3408. App.log.error("Failed to open recent items file for writing.")
  3409. self.inform.emit('[ERROR_NOTCL] %s' %
  3410. _('Failed to open recent files file for writing.'))
  3411. return
  3412. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3413. f.close()
  3414. try:
  3415. fp = open(self.data_path + '/recent_projects.json', 'w')
  3416. except IOError:
  3417. App.log.error("Failed to open recent items file for writing.")
  3418. self.inform.emit('[ERROR_NOTCL] %s' %
  3419. _('Failed to open recent projects file for writing.'))
  3420. return
  3421. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3422. fp.close()
  3423. # Re-build the recent items menu
  3424. self.setup_recent_items()
  3425. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3426. """
  3427. Creates a new specialized FlatCAMObj and attaches it to the application,
  3428. this is, updates the GUI accordingly, any other records and plots it.
  3429. This method is thread-safe.
  3430. Notes:
  3431. * If the name is in use, the self.collection will modify it
  3432. when appending it to the collection. There is no need to handle
  3433. name conflicts here.
  3434. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3435. :type kind: str
  3436. :param name: Name for the object.
  3437. :type name: str
  3438. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3439. The function is called with 2 parameters: the new object and the App instance.
  3440. :type initialize: function
  3441. :param active:
  3442. :param fit:
  3443. :param plot: If to plot the resulting object
  3444. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3445. self.colleaction
  3446. :return: None
  3447. :rtype: None
  3448. """
  3449. App.log.debug("new_object()")
  3450. obj_plot = plot
  3451. obj_autoselected = autoselected
  3452. t0 = time.time() # Debug
  3453. # ## Create object
  3454. classdict = {
  3455. "gerber": FlatCAMGerber,
  3456. "excellon": FlatCAMExcellon,
  3457. "cncjob": FlatCAMCNCjob,
  3458. "geometry": FlatCAMGeometry,
  3459. "script": FlatCAMScript,
  3460. "document": FlatCAMDocument
  3461. }
  3462. App.log.debug("Calling object constructor...")
  3463. # Object creation/instantiation
  3464. obj = classdict[kind](name)
  3465. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3466. # IMPORTANT
  3467. # The key names in defaults and options dictionary's are not random:
  3468. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3469. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3470. # copied to self.options. After that, below, depending on the type of
  3471. # object that is created, it will strip the name of the object and the underline (if the original key was
  3472. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3473. # "toolchange"
  3474. for option in self.options:
  3475. if option.find(kind + "_") == 0:
  3476. oname = option[len(kind) + 1:]
  3477. obj.options[oname] = self.options[option]
  3478. obj.isHovering = False
  3479. obj.notHovering = True
  3480. # Initialize as per user request
  3481. # User must take care to implement initialize
  3482. # in a thread-safe way as is is likely that we
  3483. # have been invoked in a separate thread.
  3484. t1 = time.time()
  3485. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3486. try:
  3487. return_value = initialize(obj, self)
  3488. except Exception as e:
  3489. msg = '[ERROR_NOTCL] %s' % \
  3490. _("An internal error has ocurred. See shell.\n")
  3491. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3492. msg += traceback.format_exc()
  3493. self.inform.emit(msg)
  3494. # if str(e) == "Empty Geometry":
  3495. # self.inform.emit("[ERROR_NOTCL] )
  3496. # else:
  3497. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3498. return "fail"
  3499. t2 = time.time()
  3500. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3501. if return_value == 'fail':
  3502. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3503. return "fail"
  3504. # Check units and convert if necessary
  3505. # This condition CAN be true because initialize() can change obj.units
  3506. if self.options["units"].upper() != obj.units.upper():
  3507. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3508. obj.convert_units(self.options["units"])
  3509. t3 = time.time()
  3510. self.log.debug("%f seconds converting units." % (t3 - t2))
  3511. # Create the bounding box for the object and then add the results to the obj.options
  3512. # But not for Scripts or for Documents
  3513. if kind != 'document' and kind != 'script':
  3514. try:
  3515. xmin, ymin, xmax, ymax = obj.bounds()
  3516. obj.options['xmin'] = xmin
  3517. obj.options['ymin'] = ymin
  3518. obj.options['xmax'] = xmax
  3519. obj.options['ymax'] = ymax
  3520. except Exception as e:
  3521. log.warning("The object has no bounds properties. %s" % str(e))
  3522. return "fail"
  3523. # update the KeyWords list with the name of the file
  3524. self.myKeywords.append(obj.options['name'])
  3525. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3526. # Move the object to the main thread and let the app know that it is available.
  3527. obj.moveToThread(self.main_thread)
  3528. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3529. return obj
  3530. def new_excellon_object(self):
  3531. """
  3532. Creates a new, blank Excellon object.
  3533. :return: None
  3534. """
  3535. self.report_usage("new_excellon_object()")
  3536. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3537. def new_geometry_object(self):
  3538. """
  3539. Creates a new, blank and single-tool Geometry object.
  3540. :return: None
  3541. """
  3542. self.report_usage("new_geometry_object()")
  3543. def initialize(obj, app):
  3544. obj.multitool = False
  3545. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3546. def new_gerber_object(self):
  3547. """
  3548. Creates a new, blank Gerber object.
  3549. :return: None
  3550. """
  3551. self.report_usage("new_gerber_object()")
  3552. def initialize(grb_obj, app):
  3553. grb_obj.multitool = False
  3554. grb_obj.source_file = []
  3555. grb_obj.multigeo = False
  3556. grb_obj.follow = False
  3557. grb_obj.apertures = {}
  3558. grb_obj.solid_geometry = []
  3559. try:
  3560. grb_obj.options['xmin'] = 0
  3561. grb_obj.options['ymin'] = 0
  3562. grb_obj.options['xmax'] = 0
  3563. grb_obj.options['ymax'] = 0
  3564. except KeyError:
  3565. pass
  3566. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3567. def new_script_object(self, name=None, text=None):
  3568. """
  3569. Creates a new, blank TCL Script object.
  3570. :param name: a name for the new object
  3571. :param text: pass a source file to the newly created script to be loaded in it
  3572. :return: None
  3573. """
  3574. self.report_usage("new_script_object()")
  3575. if text is not None:
  3576. new_source_file = text
  3577. else:
  3578. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3579. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3580. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3581. "ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3582. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3583. "ListSys, MillDrills,\n"\
  3584. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3585. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3586. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3587. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3588. "# SubtractRectangle, Version, WriteGCode\n"
  3589. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3590. '# %s:\n' % _('TCL Tutorial is here') + \
  3591. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3592. '# %s:\n' % _("FlatCAM commands list")
  3593. new_source_file += commands_list + '\n'
  3594. def initialize(obj, app):
  3595. obj.source_file = deepcopy(new_source_file)
  3596. if name is None:
  3597. outname = 'new_script'
  3598. else:
  3599. outname = name
  3600. self.new_object('script', outname, initialize, plot=False)
  3601. def new_document_object(self):
  3602. """
  3603. Creates a new, blank Document object.
  3604. :return: None
  3605. """
  3606. self.report_usage("new_document_object()")
  3607. def initialize(obj, app):
  3608. obj.source_file = ""
  3609. self.new_object('document', 'new_document', initialize, plot=False)
  3610. def on_object_created(self, obj, plot, auto_select):
  3611. """
  3612. Event callback for object creation.
  3613. It will add the new object to the collection. After that it will plot the object in a threaded way
  3614. :param obj: The newly created FlatCAM object.
  3615. :param plot: if the newly create object t obe plotted
  3616. :param auto_select: if the newly created object to be autoselected after creation
  3617. :return: None
  3618. """
  3619. t0 = time.time() # DEBUG
  3620. self.log.debug("on_object_created()")
  3621. # The Collection might change the name if there is a collision
  3622. self.collection.append(obj)
  3623. # after adding the object to the collection always update the list of objects that are in the collection
  3624. self.all_objects_list = self.collection.get_list()
  3625. # self.inform.emit('[selected] %s created & selected: %s' %
  3626. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3627. if obj.kind == 'gerber':
  3628. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3629. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3630. elif obj.kind == 'excellon':
  3631. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3632. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3633. elif obj.kind == 'cncjob':
  3634. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3635. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3636. elif obj.kind == 'geometry':
  3637. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3638. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3639. elif obj.kind == 'script':
  3640. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3641. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3642. elif obj.kind == 'document':
  3643. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3644. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3645. # update the SHELL auto-completer model with the name of the new object
  3646. self.shell._edit.set_model_data(self.myKeywords)
  3647. if auto_select:
  3648. # select the just opened object but deselect the previous ones
  3649. self.collection.set_all_inactive()
  3650. self.collection.set_active(obj.options["name"])
  3651. else:
  3652. self.collection.set_all_inactive()
  3653. # here it is done the object plotting
  3654. def worker_task(t_obj):
  3655. with self.proc_container.new(_("Plotting")):
  3656. if isinstance(t_obj, FlatCAMCNCjob):
  3657. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3658. else:
  3659. t_obj.plot()
  3660. t1 = time.time() # DEBUG
  3661. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3662. self.object_plotted.emit(t_obj)
  3663. # Send to worker
  3664. # self.worker.add_task(worker_task, [self])
  3665. if plot is True:
  3666. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3667. def on_object_changed(self, obj):
  3668. """
  3669. Called whenever the geometry of the object was changed in some way.
  3670. This require the update of it's bounding values so it can be the selected on canvas.
  3671. Update the bounding box data from obj.options
  3672. :param obj: the object that was changed
  3673. :return: None
  3674. """
  3675. xmin, ymin, xmax, ymax = obj.bounds()
  3676. obj.options['xmin'] = xmin
  3677. obj.options['ymin'] = ymin
  3678. obj.options['xmax'] = xmax
  3679. obj.options['ymax'] = ymax
  3680. log.debug("Object changed, updating the bounding box data on self.options")
  3681. # delete the old selection shape
  3682. self.delete_selection_shape()
  3683. self.should_we_save = True
  3684. def on_object_plotted(self):
  3685. """
  3686. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3687. :return: None
  3688. """
  3689. self.on_zoom_fit(None)
  3690. def on_about(self):
  3691. """
  3692. Displays the "about" dialog found in the Menu --> Help.
  3693. :return: None
  3694. """
  3695. self.report_usage("on_about")
  3696. version = self.version
  3697. version_date = self.version_date
  3698. beta = self.beta
  3699. class AboutDialog(QtWidgets.QDialog):
  3700. def __init__(self, parent=None):
  3701. QtWidgets.QDialog.__init__(self, parent)
  3702. # Icon and title
  3703. self.setWindowIcon(parent.app_icon)
  3704. self.setWindowTitle(_("About FlatCAM"))
  3705. self.resize(600, 200)
  3706. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3707. # self.setStyleSheet(
  3708. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3709. # "background-attachment: fixed"
  3710. # )
  3711. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3712. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3713. # palette = QtGui.QPalette()
  3714. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3715. # self.setPalette(palette)
  3716. logo = QtWidgets.QLabel()
  3717. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3718. title = QtWidgets.QLabel(
  3719. "<font size=8><B>FlatCAM</B></font><BR>"
  3720. "{title}<BR>"
  3721. "<BR>"
  3722. "<BR>"
  3723. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3724. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3725. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3726. "<B>{issue}</B></a><BR>".format(
  3727. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3728. devel=_("Development"),
  3729. down=_("DOWNLOAD"),
  3730. issue=_("Issue tracker"))
  3731. )
  3732. title.setOpenExternalLinks(True)
  3733. closebtn = QtWidgets.QPushButton(_("Close"))
  3734. tab_widget = QtWidgets.QTabWidget()
  3735. description_label = QtWidgets.QLabel(
  3736. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3737. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3738. version=version,
  3739. beta=('BETA' if beta else ''),
  3740. date=version_date,
  3741. arch=platform.architecture()[0])
  3742. )
  3743. description_label.setOpenExternalLinks(True)
  3744. lic_lbl_header = QtWidgets.QLabel(
  3745. '%s:<br>%s<br>' % (
  3746. _('Licensed under the MIT license'),
  3747. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3748. "http://www.opensource.org/licenses/mit-license.php</a>"
  3749. )
  3750. )
  3751. lic_lbl_header.setOpenExternalLinks(True)
  3752. lic_lbl_body = QtWidgets.QLabel(
  3753. _(
  3754. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3755. 'of this software and associated documentation files (the "Software"), to deal\n'
  3756. 'in the Software without restriction, including without limitation the rights\n'
  3757. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3758. 'copies of the Software, and to permit persons to whom the Software is\n'
  3759. 'furnished to do so, subject to the following conditions:\n\n'
  3760. 'The above copyright notice and this permission notice shall be included in\n'
  3761. 'all copies or substantial portions of the Software.\n\n'
  3762. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3763. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3764. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3765. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3766. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3767. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3768. 'THE SOFTWARE.'
  3769. )
  3770. )
  3771. attributions_label = QtWidgets.QLabel(
  3772. _(
  3773. 'Some of the icons used are from the following sources:<br>'
  3774. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3775. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3776. 'title="Flaticon">www.flaticon.com</a></div>'
  3777. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3778. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3779. )
  3780. )
  3781. # layouts
  3782. layout1 = QtWidgets.QVBoxLayout()
  3783. layout1_1 = QtWidgets.QHBoxLayout()
  3784. layout1_2 = QtWidgets.QHBoxLayout()
  3785. layout2 = QtWidgets.QHBoxLayout()
  3786. layout3 = QtWidgets.QHBoxLayout()
  3787. self.setLayout(layout1)
  3788. layout1.addLayout(layout1_1)
  3789. layout1.addLayout(layout1_2)
  3790. layout1.addLayout(layout2)
  3791. layout1.addLayout(layout3)
  3792. layout1_1.addStretch()
  3793. layout1_1.addWidget(description_label)
  3794. layout1_2.addWidget(tab_widget)
  3795. self.splash_tab = QtWidgets.QWidget()
  3796. self.splash_tab.setObjectName("splash_about")
  3797. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3798. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3799. tab_widget.addTab(self.splash_tab, _("Splash"))
  3800. self.programmmers_tab = QtWidgets.QWidget()
  3801. self.programmmers_tab.setObjectName("programmers_about")
  3802. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3803. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3804. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3805. self.translators_tab = QtWidgets.QWidget()
  3806. self.translators_tab.setObjectName("translators_about")
  3807. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3808. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3809. tab_widget.addTab(self.translators_tab, _("Translators"))
  3810. self.license_tab = QtWidgets.QWidget()
  3811. self.license_tab.setObjectName("license_about")
  3812. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3813. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3814. tab_widget.addTab(self.license_tab, _("License"))
  3815. self.attributions_tab = QtWidgets.QWidget()
  3816. self.attributions_tab.setObjectName("attributions_about")
  3817. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3818. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3819. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3820. self.splash_tab_layout.addWidget(logo, stretch=0)
  3821. self.splash_tab_layout.addWidget(title, stretch=1)
  3822. pal = QtGui.QPalette()
  3823. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3824. self.prog_grid_lay = QtWidgets.QGridLayout()
  3825. self.prog_grid_lay.setHorizontalSpacing(20)
  3826. self.prog_grid_lay.setColumnStretch(0, 0)
  3827. self.prog_grid_lay.setColumnStretch(2, 1)
  3828. prog_widget = QtWidgets.QWidget()
  3829. prog_widget.setLayout(self.prog_grid_lay)
  3830. prog_scroll = QtWidgets.QScrollArea()
  3831. prog_scroll.setWidget(prog_widget)
  3832. prog_scroll.setWidgetResizable(True)
  3833. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3834. prog_scroll.setPalette(pal)
  3835. self.programmmers_tab_layout.addWidget(prog_scroll)
  3836. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3837. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3838. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3839. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3840. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3841. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3842. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3843. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3844. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3845. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3846. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3847. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3848. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3849. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3850. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3851. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3852. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3853. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3854. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3855. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3856. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3857. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3858. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3859. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3860. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3861. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3862. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3863. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3864. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3865. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3866. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3867. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3868. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3869. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3870. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3871. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3872. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3873. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3874. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3875. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3876. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3877. self.translator_grid_lay = QtWidgets.QGridLayout()
  3878. self.translator_grid_lay.setColumnStretch(0, 0)
  3879. self.translator_grid_lay.setColumnStretch(1, 0)
  3880. self.translator_grid_lay.setColumnStretch(2, 1)
  3881. self.translator_grid_lay.setColumnStretch(3, 0)
  3882. # trans_widget = QtWidgets.QWidget()
  3883. # trans_widget.setLayout(self.translator_grid_lay)
  3884. # self.translators_tab_layout.addWidget(trans_widget)
  3885. # self.translators_tab_layout.addStretch()
  3886. trans_widget = QtWidgets.QWidget()
  3887. trans_widget.setLayout(self.translator_grid_lay)
  3888. trans_scroll = QtWidgets.QScrollArea()
  3889. trans_scroll.setWidget(trans_widget)
  3890. trans_scroll.setWidgetResizable(True)
  3891. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3892. trans_scroll.setPalette(pal)
  3893. self.translators_tab_layout.addWidget(trans_scroll)
  3894. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3895. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3896. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3897. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3898. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3899. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3900. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3901. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3902. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3903. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3904. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3905. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3906. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3907. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3908. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3909. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3910. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3911. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3912. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3913. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3914. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3915. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3916. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3917. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3918. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3919. self.translator_grid_lay.setColumnStretch(0, 0)
  3920. self.translators_tab_layout.addStretch()
  3921. self.license_tab_layout.addWidget(lic_lbl_header)
  3922. self.license_tab_layout.addWidget(lic_lbl_body)
  3923. self.license_tab_layout.addStretch()
  3924. self.attributions_tab_layout.addWidget(attributions_label)
  3925. self.attributions_tab_layout.addStretch()
  3926. layout3.addStretch()
  3927. layout3.addWidget(closebtn)
  3928. closebtn.clicked.connect(self.accept)
  3929. AboutDialog(self.ui).exec_()
  3930. def install_bookmarks(self, book_dict=None):
  3931. """
  3932. Install the bookmarks actions in the Help menu -> Bookmarks
  3933. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3934. :return: None
  3935. """
  3936. if book_dict is None:
  3937. self.defaults["global_bookmarks"].update(
  3938. {
  3939. '1': ['FlatCAM', "http://flatcam.org"],
  3940. '2': ['Backup Site', ""]
  3941. }
  3942. )
  3943. else:
  3944. self.defaults["global_bookmarks"].clear()
  3945. self.defaults["global_bookmarks"].update(book_dict)
  3946. # first try to disconnect if somehow they get connected from elsewhere
  3947. for act in self.ui.menuhelp_bookmarks.actions():
  3948. try:
  3949. act.triggered.disconnect()
  3950. except TypeError:
  3951. pass
  3952. # clear all actions except the last one who is the Bookmark manager
  3953. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3954. pass
  3955. else:
  3956. self.ui.menuhelp_bookmarks.removeAction(act)
  3957. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3958. if self.defaults["global_bookmarks"]:
  3959. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3960. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3961. # the JSON is first making the keys as strings (therefore I have to use strings too
  3962. # or do the conversion :(
  3963. # )
  3964. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3965. # the '10' entry jsut after '1' therefore ordering as strings
  3966. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3967. key=lambda x: int(x[0]))
  3968. for entry, bookmark in sorted_bookmarks:
  3969. title = bookmark[0]
  3970. weblink = bookmark[1]
  3971. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3972. act.setText(title)
  3973. act.setIcon(QtGui.QIcon('share/link16.png'))
  3974. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3975. if title == 'Backup Site' and weblink == "":
  3976. act.triggered.connect(self.on_backup_site)
  3977. else:
  3978. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3979. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3980. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3981. def on_bookmarks_manager(self):
  3982. """
  3983. Adds the bookmark manager in a Tab in Plot Area
  3984. :return:
  3985. """
  3986. for idx in range(self.ui.plot_tab_area.count()):
  3987. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3988. # there can be only one instance of Bookmark Manager at one time
  3989. return
  3990. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3991. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3992. # add the tab if it was closed
  3993. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3994. # delete the absolute and relative position and messages in the infobar
  3995. self.ui.position_label.setText("")
  3996. self.ui.rel_position_label.setText("")
  3997. # Switch plot_area to preferences page
  3998. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3999. @staticmethod
  4000. def on_backup_site():
  4001. msgbox = QtWidgets.QMessageBox()
  4002. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4003. "1. FlatCAM.org website is down\n"
  4004. "2. Someone forked FlatCAM project and wants to point\n"
  4005. "to his own website\n\n"
  4006. "If you can't get any informations about FlatCAM beta\n"
  4007. "use the YouTube channel link from the Help menu."))
  4008. msgbox.setWindowTitle(_("Alternative website"))
  4009. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  4010. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4011. msgbox.setDefaultButton(bt_yes)
  4012. msgbox.exec_()
  4013. # response = msgbox.clickedButton()
  4014. def on_file_savedefaults(self):
  4015. """
  4016. Callback for menu item File->Save Defaults. Saves application default options
  4017. ``self.defaults`` to current_defaults.FlatConfig.
  4018. :return: None
  4019. """
  4020. self.save_defaults()
  4021. # def on_app_exit(self):
  4022. # self.report_usage("on_app_exit()")
  4023. #
  4024. # if self.collection.get_list():
  4025. # msgbox = QtWidgets.QMessageBox()
  4026. # # msgbox.setText("<B>Save changes ...</B>")
  4027. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4028. # "\n"
  4029. # "Do you want to Save the project?")
  4030. # msgbox.setWindowTitle("Save changes")
  4031. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4032. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4033. # QtWidgets.QMessageBox.Cancel)
  4034. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4035. #
  4036. # response = msgbox.exec_()
  4037. #
  4038. # if response == QtWidgets.QMessageBox.Yes:
  4039. # self.on_file_saveprojectas(thread=False)
  4040. # elif response == QtWidgets.QMessageBox.Cancel:
  4041. # return
  4042. # self.save_defaults()
  4043. # else:
  4044. # self.save_defaults()
  4045. # log.debug("Application defaults saved ... Exit event.")
  4046. # QtWidgets.qApp.quit()
  4047. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4048. """
  4049. Saves application default options
  4050. ``self.defaults`` to current_defaults.FlatConfig file.
  4051. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4052. used at the next launch of the application.
  4053. :param silent: whether to display a message in status bar or not; boolean
  4054. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4055. When the application is portable it should be a mobile location.
  4056. :return: None
  4057. """
  4058. self.report_usage("save_defaults")
  4059. if data_path is None:
  4060. data_path = self.data_path
  4061. # Read options from file
  4062. try:
  4063. f = open(data_path + "/current_defaults.FlatConfig")
  4064. defaults_file_content = f.read()
  4065. f.close()
  4066. except Exception:
  4067. e = sys.exc_info()[0]
  4068. App.log.error("Could not load defaults file.")
  4069. App.log.error(str(e))
  4070. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4071. return
  4072. try:
  4073. defaults = json.loads(defaults_file_content)
  4074. except Exception:
  4075. e = sys.exc_info()[0]
  4076. App.log.error("Failed to parse defaults file.")
  4077. App.log.error(str(e))
  4078. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4079. return
  4080. # Update options
  4081. self.defaults_read_form()
  4082. defaults.update(self.defaults)
  4083. self.propagate_defaults(silent=True)
  4084. # Save the toolbar view
  4085. tb_status = 0
  4086. if self.ui.toolbarfile.isVisible():
  4087. tb_status += 1
  4088. if self.ui.toolbargeo.isVisible():
  4089. tb_status += 2
  4090. if self.ui.toolbarview.isVisible():
  4091. tb_status += 4
  4092. if self.ui.toolbartools.isVisible():
  4093. tb_status += 8
  4094. if self.ui.exc_edit_toolbar.isVisible():
  4095. tb_status += 16
  4096. if self.ui.geo_edit_toolbar.isVisible():
  4097. tb_status += 32
  4098. if self.ui.grb_edit_toolbar.isVisible():
  4099. tb_status += 64
  4100. if self.ui.snap_toolbar.isVisible():
  4101. tb_status += 128
  4102. if self.ui.toolbarshell.isVisible():
  4103. tb_status += 256
  4104. if first_time is False:
  4105. self.defaults["global_toolbar_view"] = tb_status
  4106. # Save update options
  4107. try:
  4108. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4109. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4110. f.close()
  4111. except Exception as e:
  4112. log.debug("App.save_defaults() --> %s" % str(e))
  4113. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4114. return
  4115. if not silent:
  4116. self.inform.emit('[success] %s' % _("Preferences saved."))
  4117. def save_factory_defaults(self, silent_message=False, data_path=None):
  4118. """
  4119. Saves application factory default options
  4120. ``self.defaults`` to factory_defaults.FlatConfig.
  4121. It's a one time job done just after the first install.
  4122. :param silent_message: whether to display a message in status bar or not; boolean
  4123. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4124. When the application is portable it should be a mobile location.
  4125. :return: None
  4126. """
  4127. self.report_usage("save_factory_defaults")
  4128. if data_path is None:
  4129. data_path = self.data_path
  4130. # Read options from file
  4131. try:
  4132. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4133. factory_defaults_file_content = f_f_def.read()
  4134. f_f_def.close()
  4135. except Exception:
  4136. e = sys.exc_info()[0]
  4137. App.log.error("Could not load factory defaults file.")
  4138. App.log.error(str(e))
  4139. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4140. return
  4141. try:
  4142. factory_defaults = json.loads(factory_defaults_file_content)
  4143. except Exception:
  4144. e = sys.exc_info()[0]
  4145. App.log.error("Failed to parse factory defaults file.")
  4146. App.log.error(str(e))
  4147. if silent_message is False:
  4148. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4149. return
  4150. # Update options
  4151. self.defaults_read_form()
  4152. factory_defaults.update(self.defaults)
  4153. self.propagate_defaults(silent=True)
  4154. # Save update options
  4155. try:
  4156. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4157. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4158. f_f_def_s.close()
  4159. except Exception as e:
  4160. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4161. if silent_message is False:
  4162. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4163. return
  4164. if silent_message is False:
  4165. self.inform.emit(_("Factory defaults saved."))
  4166. def final_save(self):
  4167. """
  4168. Callback for doing a preferences save to file whenever the application is about to quit.
  4169. If the project has changes, it will ask the user to save the project.
  4170. :return: None
  4171. """
  4172. if self.save_in_progress:
  4173. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4174. return
  4175. if self.should_we_save and self.collection.get_list():
  4176. msgbox = QtWidgets.QMessageBox()
  4177. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4178. "\n"
  4179. "Do you want to Save the project?"))
  4180. msgbox.setWindowTitle(_("Save changes"))
  4181. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4182. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4183. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4184. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4185. msgbox.setDefaultButton(bt_yes)
  4186. msgbox.exec_()
  4187. response = msgbox.clickedButton()
  4188. if response == bt_yes:
  4189. try:
  4190. self.trayIcon.hide()
  4191. except Exception:
  4192. pass
  4193. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4194. elif response == bt_no:
  4195. try:
  4196. self.trayIcon.hide()
  4197. except Exception:
  4198. pass
  4199. self.quit_application()
  4200. elif response == bt_cancel:
  4201. return
  4202. else:
  4203. try:
  4204. self.trayIcon.hide()
  4205. except Exception:
  4206. pass
  4207. self.quit_application()
  4208. def quit_application(self):
  4209. """
  4210. Called (as a pyslot or not) when the application is quit.
  4211. :return: None
  4212. """
  4213. self.save_defaults()
  4214. log.debug("App.final_save() --> App Defaults saved.")
  4215. if self.cmd_line_headless != 1:
  4216. # save app state to file
  4217. stgs = QSettings("Open Source", "FlatCAM")
  4218. stgs.setValue('saved_gui_state', self.ui.saveState())
  4219. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4220. stgs.setValue(
  4221. 'language',
  4222. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4223. )
  4224. stgs.setValue(
  4225. 'notebook_font_size',
  4226. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4227. )
  4228. stgs.setValue(
  4229. 'axis_font_size',
  4230. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4231. )
  4232. stgs.setValue(
  4233. 'textbox_font_size',
  4234. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4235. )
  4236. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4237. stgs.setValue(
  4238. 'machinist',
  4239. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4240. )
  4241. # This will write the setting to the platform specific storage.
  4242. del stgs
  4243. log.debug("App.final_save() --> App UI state saved.")
  4244. QtWidgets.qApp.quit()
  4245. def on_portable_checked(self, state):
  4246. """
  4247. Callback called when the checkbox in Preferences GUI is checked.
  4248. It will set the application as portable by creating the preferences and recent files in the
  4249. 'config' folder found in the FlatCAM installation folder.
  4250. :param state: boolean, the state of the checkbox when clicked/checked
  4251. :return:
  4252. """
  4253. line_no = 0
  4254. data = None
  4255. if sys.platform != 'win32':
  4256. # this won't work in Linux or MacOS
  4257. return
  4258. # test if the app was frozen and choose the path for the configuration file
  4259. if getattr(sys, "frozen", False) is True:
  4260. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4261. else:
  4262. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4263. config_file = current_data_path + '\\configuration.txt'
  4264. try:
  4265. with open(config_file, 'r') as f:
  4266. try:
  4267. data = f.readlines()
  4268. except Exception as e:
  4269. log.debug('App.__init__() -->%s' % str(e))
  4270. return
  4271. except FileNotFoundError:
  4272. pass
  4273. for line in data:
  4274. line = line.strip('\n')
  4275. param = str(line).rpartition('=')
  4276. if param[0] == 'portable':
  4277. break
  4278. line_no += 1
  4279. if state:
  4280. data[line_no] = 'portable=True\n'
  4281. # create the new defauults files
  4282. # create current_defaults.FlatConfig file if there is none
  4283. try:
  4284. f = open(current_data_path + '/current_defaults.FlatConfig')
  4285. f.close()
  4286. except IOError:
  4287. App.log.debug('Creating empty current_defaults.FlatConfig')
  4288. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4289. json.dump({}, f)
  4290. f.close()
  4291. # create factory_defaults.FlatConfig file if there is none
  4292. try:
  4293. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4294. f.close()
  4295. except IOError:
  4296. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4297. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4298. json.dump({}, f)
  4299. f.close()
  4300. try:
  4301. f = open(current_data_path + '/recent.json')
  4302. f.close()
  4303. except IOError:
  4304. App.log.debug('Creating empty recent.json')
  4305. f = open(current_data_path + '/recent.json', 'w')
  4306. json.dump([], f)
  4307. f.close()
  4308. try:
  4309. fp = open(current_data_path + '/recent_projects.json')
  4310. fp.close()
  4311. except IOError:
  4312. App.log.debug('Creating empty recent_projects.json')
  4313. fp = open(current_data_path + '/recent_projects.json', 'w')
  4314. json.dump([], fp)
  4315. fp.close()
  4316. # save the current defaults to the new defaults file
  4317. self.save_defaults(silent=True, data_path=current_data_path)
  4318. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4319. else:
  4320. data[line_no] = 'portable=False\n'
  4321. with open(config_file, 'w') as f:
  4322. f.writelines(data)
  4323. def on_toggle_shell(self):
  4324. """
  4325. Toggle shell: if is visible close it, if it is closed then open it
  4326. :return: None
  4327. """
  4328. self.report_usage("on_toggle_shell()")
  4329. if self.ui.shell_dock.isVisible():
  4330. self.ui.shell_dock.hide()
  4331. else:
  4332. self.ui.shell_dock.show()
  4333. def on_register_files(self, obj_type=None):
  4334. """
  4335. Called whenever there is a need to register file extensions with FlatCAM.
  4336. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4337. :param obj_type: the type of object to be register for.
  4338. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4339. :return: None
  4340. """
  4341. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4342. new_reg_path = 'Software\\Classes\\'
  4343. # find if the current user is admin
  4344. try:
  4345. is_admin = os.getuid() == 0
  4346. except AttributeError:
  4347. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4348. if is_admin is True:
  4349. root_path = winreg.HKEY_LOCAL_MACHINE
  4350. else:
  4351. root_path = winreg.HKEY_CURRENT_USER
  4352. # create the keys
  4353. def set_reg(name, root_path, new_reg_path, value):
  4354. try:
  4355. winreg.CreateKey(root_path, new_reg_path)
  4356. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4357. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4358. return True
  4359. except WindowsError:
  4360. return False
  4361. # delete key in registry
  4362. def delete_reg(root_path, reg_path, key_to_del):
  4363. key_to_del_path = reg_path + key_to_del
  4364. try:
  4365. winreg.DeleteKey(root_path, key_to_del_path)
  4366. return True
  4367. except WindowsError:
  4368. return False
  4369. if obj_type is None or obj_type == 'excellon':
  4370. exc_list = \
  4371. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4372. exc_list = [x for x in exc_list if x != '']
  4373. # register all keys in the Preferences window
  4374. for ext in exc_list:
  4375. new_k = new_reg_path + '.%s' % ext
  4376. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4377. # and unregister those that are no longer in the Preferences windows but are in the file
  4378. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4379. if ext not in exc_list:
  4380. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4381. # now write the updated extensions to the self.defaults
  4382. # new_ext = ''
  4383. # for ext in exc_list:
  4384. # new_ext = new_ext + ext + ', '
  4385. # self.defaults["fa_excellon"] = new_ext
  4386. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4387. if obj_type is None or obj_type == 'gcode':
  4388. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4389. gco_list = [x for x in gco_list if x != '']
  4390. # register all keys in the Preferences window
  4391. for ext in gco_list:
  4392. new_k = new_reg_path + '.%s' % ext
  4393. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4394. # and unregister those that are no longer in the Preferences windows but are in the file
  4395. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4396. if ext not in gco_list:
  4397. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4398. # now write the updated extensions to the self.defaults
  4399. # new_ext = ''
  4400. # for ext in gco_list:
  4401. # new_ext = new_ext + ext + ', '
  4402. # self.defaults["fa_gcode"] = new_ext
  4403. self.inform.emit('[success] %s' %
  4404. _("Selected GCode file extensions registered with FlatCAM."))
  4405. if obj_type is None or obj_type == 'gerber':
  4406. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4407. grb_list = [x for x in grb_list if x != '']
  4408. # register all keys in the Preferences window
  4409. for ext in grb_list:
  4410. new_k = new_reg_path + '.%s' % ext
  4411. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4412. # and unregister those that are no longer in the Preferences windows but are in the file
  4413. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4414. if ext not in grb_list:
  4415. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4416. # now write the updated extensions to the self.defaults
  4417. # new_ext = ''
  4418. # for ext in grb_list:
  4419. # new_ext = new_ext + ext + ', '
  4420. # self.defaults["fa_gerber"] = new_ext
  4421. self.inform.emit('[success] %s' %
  4422. _("Selected Gerber file extensions registered with FlatCAM."))
  4423. def add_extension(self, ext_type):
  4424. """
  4425. Add a file extension to the list for a specific object
  4426. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4427. :return:
  4428. """
  4429. if ext_type == 'excellon':
  4430. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4431. if new_ext == '':
  4432. return
  4433. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4434. if new_ext in old_val:
  4435. return
  4436. old_val.append(new_ext)
  4437. old_val.sort()
  4438. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4439. if ext_type == 'gcode':
  4440. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4441. if new_ext == '':
  4442. return
  4443. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4444. if new_ext in old_val:
  4445. return
  4446. old_val.append(new_ext)
  4447. old_val.sort()
  4448. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4449. if ext_type == 'gerber':
  4450. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4451. if new_ext == '':
  4452. return
  4453. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4454. if new_ext in old_val:
  4455. return
  4456. old_val.append(new_ext)
  4457. old_val.sort()
  4458. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4459. if ext_type == 'keyword':
  4460. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4461. if new_kw == '':
  4462. return
  4463. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4464. if new_kw in old_val:
  4465. return
  4466. old_val.append(new_kw)
  4467. old_val.sort()
  4468. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4469. # update the self.myKeywords so the model is updated
  4470. self.autocomplete_kw_list = \
  4471. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4472. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4473. self.shell._edit.set_model_data(self.myKeywords)
  4474. def del_extension(self, ext_type):
  4475. """
  4476. Remove a file extension from the list for a specific object
  4477. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4478. :return:
  4479. """
  4480. if ext_type == 'excellon':
  4481. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4482. if new_ext == '':
  4483. return
  4484. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4485. if new_ext not in old_val:
  4486. return
  4487. old_val.remove(new_ext)
  4488. old_val.sort()
  4489. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4490. if ext_type == 'gcode':
  4491. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4492. if new_ext == '':
  4493. return
  4494. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4495. if new_ext not in old_val:
  4496. return
  4497. old_val.remove(new_ext)
  4498. old_val.sort()
  4499. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4500. if ext_type == 'gerber':
  4501. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4502. if new_ext == '':
  4503. return
  4504. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4505. if new_ext not in old_val:
  4506. return
  4507. old_val.remove(new_ext)
  4508. old_val.sort()
  4509. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4510. if ext_type == 'keyword':
  4511. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4512. if new_kw == '':
  4513. return
  4514. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4515. if new_kw not in old_val:
  4516. return
  4517. old_val.remove(new_kw)
  4518. old_val.sort()
  4519. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4520. # update the self.myKeywords so the model is updated
  4521. self.autocomplete_kw_list = \
  4522. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4523. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4524. self.shell._edit.set_model_data(self.myKeywords)
  4525. def restore_extensions(self, ext_type):
  4526. """
  4527. Restore all file extensions associations with FlatCAM, for a specific object
  4528. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4529. :return:
  4530. """
  4531. if ext_type == 'excellon':
  4532. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4533. # for the ability to open Excellon files with .txt extension
  4534. new_exc_list = deepcopy(self.exc_list)
  4535. try:
  4536. new_exc_list.remove('txt')
  4537. except ValueError:
  4538. pass
  4539. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4540. if ext_type == 'gcode':
  4541. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4542. if ext_type == 'gerber':
  4543. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4544. if ext_type == 'keyword':
  4545. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4546. # update the self.myKeywords so the model is updated
  4547. self.autocomplete_kw_list = self.default_keywords
  4548. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4549. self.shell._edit.set_model_data(self.myKeywords)
  4550. def delete_all_extensions(self, ext_type):
  4551. """
  4552. Delete all file extensions associations with FlatCAM, for a specific object
  4553. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4554. :return:
  4555. """
  4556. if ext_type == 'excellon':
  4557. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4558. if ext_type == 'gcode':
  4559. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4560. if ext_type == 'gerber':
  4561. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4562. if ext_type == 'keyword':
  4563. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4564. # update the self.myKeywords so the model is updated
  4565. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4566. self.shell._edit.set_model_data(self.myKeywords)
  4567. def on_edit_join(self, name=None):
  4568. """
  4569. Callback for Edit->Join. Joins the selected geometry objects into
  4570. a new one.
  4571. :return: None
  4572. """
  4573. self.report_usage("on_edit_join()")
  4574. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4575. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4576. geo_type_set = set()
  4577. objs = self.collection.get_selected()
  4578. if len(objs) < 2:
  4579. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4580. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4581. return 'fail'
  4582. for obj in objs:
  4583. geo_type_set.add(obj.multigeo)
  4584. # if len(geo_type_list) == 1 means that all list elements are the same
  4585. if len(geo_type_set) != 1:
  4586. self.inform.emit('[ERROR] %s' %
  4587. _("Failed join. The Geometry objects are of different types.\n"
  4588. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4589. "convert from one to another and retry joining \n"
  4590. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4591. "the result may not be what was expected. \n"
  4592. "Check the generated GCODE."))
  4593. return
  4594. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4595. if True in geo_type_set:
  4596. def initialize(geo_obj, app):
  4597. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4598. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4599. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4600. for v in obj.tools.values():
  4601. v['data']['name'] = obj_name_multi
  4602. self.new_object("geometry", obj_name_multi, initialize)
  4603. else:
  4604. def initialize(geo_obj, app):
  4605. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4606. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4607. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4608. for v in obj.tools.values():
  4609. v['data']['name'] = obj_name_single
  4610. self.new_object("geometry", obj_name_single, initialize)
  4611. self.should_we_save = True
  4612. def on_edit_join_exc(self):
  4613. """
  4614. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4615. a new Excellon.
  4616. :return: None
  4617. """
  4618. self.report_usage("on_edit_join_exc()")
  4619. objs = self.collection.get_selected()
  4620. for obj in objs:
  4621. if not isinstance(obj, FlatCAMExcellon):
  4622. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4623. return
  4624. if len(objs) < 2:
  4625. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4626. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4627. return 'fail'
  4628. def initialize(exc_obj, app):
  4629. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4630. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4631. self.new_object("excellon", 'Combo_Excellon', initialize)
  4632. self.should_we_save = True
  4633. def on_edit_join_grb(self):
  4634. """
  4635. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4636. a new Gerber object.
  4637. :return: None
  4638. """
  4639. self.report_usage("on_edit_join_grb()")
  4640. objs = self.collection.get_selected()
  4641. for obj in objs:
  4642. if not isinstance(obj, FlatCAMGerber):
  4643. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4644. return
  4645. if len(objs) < 2:
  4646. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4647. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4648. return 'fail'
  4649. def initialize(grb_obj, app):
  4650. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4651. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4652. self.new_object("gerber", 'Combo_Gerber', initialize)
  4653. self.should_we_save = True
  4654. def on_convert_singlegeo_to_multigeo(self):
  4655. """
  4656. Called for converting a Geometry object from single-geo to multi-geo.
  4657. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4658. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4659. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4660. the solid-geometry of that tool.
  4661. :return: None
  4662. """
  4663. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4664. obj = self.collection.get_active()
  4665. if obj is None:
  4666. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4667. return
  4668. if not isinstance(obj, FlatCAMGeometry):
  4669. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4670. return
  4671. obj.multigeo = True
  4672. for tooluid, dict_value in obj.tools.items():
  4673. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4674. if not isinstance(obj.solid_geometry, list):
  4675. obj.solid_geometry = [obj.solid_geometry]
  4676. obj.solid_geometry[:] = []
  4677. obj.plot()
  4678. self.should_we_save = True
  4679. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4680. def on_convert_multigeo_to_singlegeo(self):
  4681. """
  4682. Called for converting a Geometry object from multi-geo to single-geo.
  4683. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4684. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4685. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4686. the solid-geometry of that tool.
  4687. :return: None
  4688. """
  4689. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4690. obj = self.collection.get_active()
  4691. if obj is None:
  4692. self.inform.emit('[ERROR_NOTCL] %s' %
  4693. _("Failed. Select a Geometry Object and try again."))
  4694. return
  4695. if not isinstance(obj, FlatCAMGeometry):
  4696. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4697. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4698. return
  4699. obj.multigeo = False
  4700. total_solid_geometry = []
  4701. for tooluid, dict_value in obj.tools.items():
  4702. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4703. # clear the original geometry
  4704. dict_value['solid_geometry'][:] = []
  4705. obj.solid_geometry = deepcopy(total_solid_geometry)
  4706. obj.plot()
  4707. self.should_we_save = True
  4708. self.inform.emit('[success] %s' %
  4709. _("A Geometry object was converted to SingleGeo type."))
  4710. def on_defaults_dict_change(self, field):
  4711. """
  4712. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4713. Edit -> Preferences tab window.
  4714. :param field: the key of the self.defaults dictionary that was changed.
  4715. :return: None
  4716. """
  4717. self.defaults_write_form_field(field)
  4718. if field == "units":
  4719. self.set_screen_units(self.defaults['units'])
  4720. def set_screen_units(self, units):
  4721. """
  4722. Set the FlatCAM units on the status bar.
  4723. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4724. :return: None
  4725. """
  4726. self.ui.units_label.setText("[" + units.lower() + "]")
  4727. def on_toggle_units_click(self):
  4728. try:
  4729. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4730. except (TypeError, AttributeError):
  4731. pass
  4732. if self.defaults["units"] == 'MM':
  4733. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4734. else:
  4735. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4736. self.on_toggle_units(no_pref=True)
  4737. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4738. lambda: self.on_toggle_units(no_pref=False))
  4739. def on_toggle_units(self, no_pref=False):
  4740. """
  4741. Callback for the Units radio-button change in the Preferences tab.
  4742. Changes the application's default units adn for the project too.
  4743. If changing the project's units, the change propagates to all of
  4744. the objects in the project.
  4745. :return: None
  4746. """
  4747. self.report_usage("on_toggle_units")
  4748. if self.toggle_units_ignore:
  4749. return
  4750. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4751. # If option is the same, then ignore
  4752. if new_units == self.defaults["units"].upper():
  4753. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4754. return
  4755. # Options to scale
  4756. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4757. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4758. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4759. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4760. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4761. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4762. "excellon_editor_slot_lin_pitch",
  4763. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4764. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4765. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4766. "geometry_feedrate_probe", "geometry_startz",
  4767. 'cncjob_tooldia',
  4768. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4769. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4770. "tools_nccnewdia",
  4771. "tools_2sided_drilldia", "tools_film_boundary",
  4772. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4773. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4774. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4775. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4776. "tools_transform_offset_y",
  4777. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4778. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4779. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4780. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4781. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4782. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4783. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4784. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4785. "tools_fiducials_line_thickness",
  4786. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4787. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4788. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4789. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4790. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4791. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4792. def scale_defaults(sfactor):
  4793. for dim in dimensions:
  4794. if dim == 'excellon_toolchangexy':
  4795. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4796. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4797. coords_xy[0] *= sfactor
  4798. coords_xy[1] *= sfactor
  4799. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4800. self.decimals, coords_xy[1])
  4801. elif dim == 'geometry_toolchangexy':
  4802. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4803. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4804. coords_xy[0] *= sfactor
  4805. coords_xy[1] *= sfactor
  4806. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4807. self.decimals, coords_xy[1])
  4808. elif dim == 'geometry_cnctooldia':
  4809. tools_diameters = []
  4810. try:
  4811. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4812. tools_diameters = [eval(a) for a in tools_string if a != '']
  4813. except Exception as e:
  4814. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4815. self.defaults['geometry_cnctooldia'] = ''
  4816. for t in range(len(tools_diameters)):
  4817. tools_diameters[t] *= sfactor
  4818. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4819. elif dim == 'tools_ncctools':
  4820. ncctools = []
  4821. try:
  4822. tools_string = self.defaults["tools_ncctools"].split(",")
  4823. ncctools = [eval(a) for a in tools_string if a != '']
  4824. except Exception as e:
  4825. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4826. self.defaults['tools_ncctools'] = ''
  4827. for t in range(len(ncctools)):
  4828. ncctools[t] *= sfactor
  4829. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4830. elif dim == 'tools_solderpaste_tools':
  4831. sptools = []
  4832. try:
  4833. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4834. sptools = [eval(a) for a in tools_string if a != '']
  4835. except Exception as e:
  4836. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4837. self.defaults['tools_solderpaste_tools'] = ""
  4838. for t in range(len(sptools)):
  4839. sptools[t] *= sfactor
  4840. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4841. elif dim == 'tools_solderpaste_xy_toolchange':
  4842. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4843. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4844. sp_coords[0] *= sfactor
  4845. sp_coords[1] *= sfactor
  4846. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4847. self.decimals, sp_coords[1])
  4848. elif dim == 'global_gridx' or dim == 'global_gridy':
  4849. if new_units == 'IN':
  4850. val = 0.1
  4851. try:
  4852. val = float(self.defaults[dim]) * sfactor
  4853. except Exception as e:
  4854. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4855. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4856. else:
  4857. val = 0.1
  4858. try:
  4859. val = float(self.defaults[dim]) * sfactor
  4860. except Exception as e:
  4861. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4862. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4863. else:
  4864. val = 0.1
  4865. if self.defaults[dim]:
  4866. try:
  4867. val = float(self.defaults[dim]) * sfactor
  4868. except Exception as e:
  4869. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4870. self.defaults[dim] = val
  4871. # The scaling factor depending on choice of units.
  4872. factor = 25.4 if new_units == 'MM' else 1/25.4
  4873. # Changing project units. Warn user.
  4874. msgbox = QtWidgets.QMessageBox()
  4875. msgbox.setWindowTitle(_("Toggle Units"))
  4876. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4877. msgbox.setText(_("Changing the units of the project\n"
  4878. "will scale all objects.\n\n"
  4879. "Do you want to continue?"))
  4880. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4881. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4882. msgbox.setDefaultButton(bt_ok)
  4883. msgbox.exec_()
  4884. response = msgbox.clickedButton()
  4885. if response == bt_ok:
  4886. if no_pref is False:
  4887. self.defaults_read_form()
  4888. scale_defaults(factor)
  4889. self.defaults_write_form(fl_units=new_units)
  4890. self.defaults["units"] = new_units
  4891. # update the defaults from form, some may assume that the conversion is enough and it's not
  4892. self.on_options_app2project()
  4893. # update the objects
  4894. for obj in self.collection.get_list():
  4895. obj.convert_units(new_units)
  4896. # make that the properties stored in the object are also updated
  4897. self.object_changed.emit(obj)
  4898. # rebuild the object UI
  4899. obj.build_ui()
  4900. # change this only if the workspace is active
  4901. if self.defaults['global_workspace'] is True:
  4902. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4903. # adjust the grid values on the main toolbar
  4904. val_x = float(self.defaults['global_gridx']) * factor
  4905. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4906. current = self.collection.get_active()
  4907. if current is not None:
  4908. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4909. if not isinstance(current, FlatCAMGeometry):
  4910. current.to_form()
  4911. # replot all objects
  4912. self.plot_all()
  4913. # set the status labels to reflect the current FlatCAM units
  4914. self.set_screen_units(new_units)
  4915. # signal to the app that we changed the object properties and it shoud save the project
  4916. self.should_we_save = True
  4917. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4918. else:
  4919. # Undo toggling
  4920. self.toggle_units_ignore = True
  4921. if self.defaults['units'].upper() == 'MM':
  4922. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4923. else:
  4924. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4925. self.toggle_units_ignore = False
  4926. # store the grid values so they are not changed in the next step
  4927. val_x = float(self.defaults['global_gridx'])
  4928. val_y = float(self.defaults['global_gridy'])
  4929. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  4930. self.defaults_read_form()
  4931. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4932. # I don't want it for the grid values, so I update them here
  4933. self.defaults['global_gridx'] = val_x
  4934. self.defaults['global_gridy'] = val_y
  4935. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4936. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4937. def on_fullscreen(self, disable=False):
  4938. self.report_usage("on_fullscreen()")
  4939. if self.toggle_fscreen is False and disable is False:
  4940. # self.ui.showFullScreen()
  4941. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4942. a = self.ui.geometry()
  4943. self.x_pos = a.x()
  4944. self.y_pos = a.y()
  4945. self.width = a.width()
  4946. self.height = a.height()
  4947. # set new geometry to full desktop rect
  4948. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4949. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4950. # everything else will not work without this hack. This happen in Windows.
  4951. # https://bugreports.qt.io/browse/QTBUG-41309
  4952. desktop = QtWidgets.QApplication.desktop()
  4953. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4954. rec = desktop.screenGeometry(screen)
  4955. x = rec.x() - 1
  4956. y = rec.y() - 1
  4957. h = rec.height() + 2
  4958. w = rec.width() + 2
  4959. self.ui.setGeometry(x, y, w, h)
  4960. self.ui.show()
  4961. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4962. tb.setVisible(False)
  4963. self.ui.splitter_left.setVisible(False)
  4964. self.toggle_fscreen = True
  4965. elif self.toggle_fscreen is True or disable is True:
  4966. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4967. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4968. self.ui.showNormal()
  4969. self.restore_toolbar_view()
  4970. self.ui.splitter_left.setVisible(True)
  4971. self.toggle_fscreen = False
  4972. def on_toggle_plotarea(self):
  4973. self.report_usage("on_toggle_plotarea()")
  4974. try:
  4975. name = self.ui.plot_tab_area.widget(0).objectName()
  4976. except AttributeError:
  4977. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4978. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4979. self.ui.plot_tab_area.protectTab(0)
  4980. return
  4981. if name != 'plotarea':
  4982. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4983. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4984. self.ui.plot_tab_area.protectTab(0)
  4985. else:
  4986. self.ui.plot_tab_area.closeTab(0)
  4987. def on_toggle_notebook(self):
  4988. if self.ui.splitter.sizes()[0] == 0:
  4989. self.ui.splitter.setSizes([1, 1])
  4990. self.ui.menu_toggle_nb.setChecked(True)
  4991. else:
  4992. self.ui.splitter.setSizes([0, 1])
  4993. self.ui.menu_toggle_nb.setChecked(False)
  4994. def on_toggle_axis(self):
  4995. self.report_usage("on_toggle_axis()")
  4996. if self.toggle_axis is False:
  4997. if self.is_legacy is False:
  4998. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4999. parent=self.plotcanvas.view.scene)
  5000. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5001. parent=self.plotcanvas.view.scene)
  5002. else:
  5003. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  5004. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  5005. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5006. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5007. self.plotcanvas.canvas.draw()
  5008. self.toggle_axis = True
  5009. else:
  5010. if self.is_legacy is False:
  5011. self.plotcanvas.v_line.parent = None
  5012. self.plotcanvas.h_line.parent = None
  5013. else:
  5014. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5015. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5016. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5017. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5018. self.plotcanvas.canvas.draw()
  5019. self.toggle_axis = False
  5020. def on_toggle_grid(self):
  5021. self.report_usage("on_toggle_grid()")
  5022. self.ui.grid_snap_btn.trigger()
  5023. def on_toggle_grid_lines(self):
  5024. self.report_usage("on_toggle_grd_lines()")
  5025. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5026. if tt_settings.contains("theme"):
  5027. theme = tt_settings.value('theme', type=str)
  5028. else:
  5029. theme = 'white'
  5030. if self.toggle_grid_lines is False:
  5031. if self.is_legacy is False:
  5032. if theme == 'white':
  5033. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5034. else:
  5035. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5036. else:
  5037. self.plotcanvas.axes.grid(True)
  5038. try:
  5039. self.plotcanvas.canvas.draw()
  5040. except IndexError:
  5041. pass
  5042. pass
  5043. self.toggle_grid_lines = True
  5044. else:
  5045. if self.is_legacy is False:
  5046. if theme == 'white':
  5047. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5048. else:
  5049. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5050. else:
  5051. self.plotcanvas.axes.grid(False)
  5052. try:
  5053. self.plotcanvas.canvas.draw()
  5054. except IndexError:
  5055. pass
  5056. self.toggle_grid_lines = False
  5057. if self.is_legacy is False:
  5058. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5059. # - perhaps is a bug in VisPy implementation
  5060. if self.grid_status() is True:
  5061. self.app_cursor.enabled = False
  5062. self.app_cursor.enabled = True
  5063. else:
  5064. self.app_cursor.enabled = True
  5065. self.app_cursor.enabled = False
  5066. def show_preferences_gui(self):
  5067. """
  5068. Called to initialize and show the Preferences GUI
  5069. :return: None
  5070. """
  5071. self.gen_form = self.ui.general_defaults_form
  5072. self.ger_form = self.ui.gerber_defaults_form
  5073. self.exc_form = self.ui.excellon_defaults_form
  5074. self.geo_form = self.ui.geometry_defaults_form
  5075. self.cnc_form = self.ui.cncjob_defaults_form
  5076. self.tools_form = self.ui.tools_defaults_form
  5077. self.tools2_form = self.ui.tools2_defaults_form
  5078. self.fa_form = self.ui.util_defaults_form
  5079. try:
  5080. self.ui.general_scroll_area.takeWidget()
  5081. except Exception:
  5082. self.log.debug("Nothing to remove")
  5083. self.ui.general_scroll_area.setWidget(self.gen_form)
  5084. self.gen_form.show()
  5085. try:
  5086. self.ui.gerber_scroll_area.takeWidget()
  5087. except Exception:
  5088. self.log.debug("Nothing to remove")
  5089. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5090. self.ger_form.show()
  5091. try:
  5092. self.ui.excellon_scroll_area.takeWidget()
  5093. except Exception:
  5094. self.log.debug("Nothing to remove")
  5095. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5096. self.exc_form.show()
  5097. try:
  5098. self.ui.geometry_scroll_area.takeWidget()
  5099. except Exception:
  5100. self.log.debug("Nothing to remove")
  5101. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5102. self.geo_form.show()
  5103. try:
  5104. self.ui.cncjob_scroll_area.takeWidget()
  5105. except Exception:
  5106. self.log.debug("Nothing to remove")
  5107. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5108. self.cnc_form.show()
  5109. try:
  5110. self.ui.tools_scroll_area.takeWidget()
  5111. except Exception:
  5112. self.log.debug("Nothing to remove")
  5113. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5114. self.tools_form.show()
  5115. try:
  5116. self.ui.tools2_scroll_area.takeWidget()
  5117. except Exception:
  5118. self.log.debug("Nothing to remove")
  5119. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5120. self.tools2_form.show()
  5121. try:
  5122. self.ui.fa_scroll_area.takeWidget()
  5123. except Exception:
  5124. self.log.debug("Nothing to remove")
  5125. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5126. self.fa_form.show()
  5127. self.log.debug("Finished Preferences GUI form initialization.")
  5128. # self.options2form()
  5129. def init_color_pickers_in_preferences_gui(self):
  5130. # Init Plot Colors
  5131. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5132. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5133. "background-color:%s;"
  5134. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5135. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5136. int(self.defaults['global_plot_fill'][7:9], 16))
  5137. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5138. int(self.defaults['global_plot_fill'][7:9], 16))
  5139. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5140. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5141. "background-color:%s;"
  5142. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5143. # Init Left-Right Selection colors
  5144. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5145. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5146. "background-color:%s;"
  5147. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5148. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5149. int(self.defaults['global_sel_fill'][7:9], 16))
  5150. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5151. int(self.defaults['global_sel_fill'][7:9], 16))
  5152. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5153. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5154. "background-color:%s;"
  5155. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5156. # Init Right-Left Selection colors
  5157. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5158. self.defaults['global_alt_sel_fill'])
  5159. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5160. "background-color:%s;"
  5161. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5162. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5163. int(self.defaults['global_sel_fill'][7:9], 16))
  5164. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5165. int(self.defaults['global_sel_fill'][7:9], 16))
  5166. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5167. self.defaults['global_alt_sel_line'])
  5168. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5169. "background-color:%s;"
  5170. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5171. # Init Draw color and Selection Draw Color
  5172. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5173. self.defaults['global_draw_color'])
  5174. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5175. "background-color:%s;"
  5176. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5177. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5178. self.defaults['global_sel_draw_color'])
  5179. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5180. "background-color:%s;"
  5181. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5182. # Init Project Items color
  5183. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5184. self.defaults['global_proj_item_color'])
  5185. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5186. "background-color:%s;"
  5187. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5188. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5189. self.defaults['global_proj_item_dis_color'])
  5190. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5191. "background-color:%s;"
  5192. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5193. # Init the Annotation CNC Job color
  5194. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5195. self.defaults['cncjob_annotation_fontcolor'])
  5196. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5197. "background-color:%s;"
  5198. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5199. # Init the Tool Film color
  5200. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5201. self.defaults['tools_film_color'])
  5202. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5203. "background-color:%s;"
  5204. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5205. )
  5206. # Init the Tool QRCode colors
  5207. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5208. self.defaults['tools_qrcode_fill_color'])
  5209. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5210. "background-color:%s;"
  5211. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5212. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5213. self.defaults['tools_qrcode_back_color'])
  5214. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5215. "background-color:%s;"
  5216. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5217. def on_excellon_defaults_button(self):
  5218. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5219. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5220. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5221. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5222. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5223. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5224. log.debug("Excellon app defaults loaded ...")
  5225. def on_update_exc_export(self, state):
  5226. """
  5227. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5228. if the update_excellon_cb checkbox is checked
  5229. :param state: state of the checkbox whose signals is tied to his slot
  5230. :return:
  5231. """
  5232. if state:
  5233. # first try to disconnect
  5234. try:
  5235. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5236. disconnect(self.on_excellon_format_changed)
  5237. except TypeError:
  5238. pass
  5239. try:
  5240. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5241. disconnect(self.on_excellon_format_changed)
  5242. except TypeError:
  5243. pass
  5244. try:
  5245. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5246. disconnect(self.on_excellon_format_changed)
  5247. except TypeError:
  5248. pass
  5249. try:
  5250. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5251. disconnect(self.on_excellon_format_changed)
  5252. except TypeError:
  5253. pass
  5254. try:
  5255. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5256. disconnect(self.on_excellon_zeros_changed)
  5257. except TypeError:
  5258. pass
  5259. try:
  5260. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5261. disconnect(self.on_excellon_zeros_changed)
  5262. except TypeError:
  5263. pass
  5264. # the connect them
  5265. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5266. self.on_excellon_format_changed)
  5267. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5268. self.on_excellon_format_changed)
  5269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5270. self.on_excellon_format_changed)
  5271. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5272. self.on_excellon_format_changed)
  5273. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5274. self.on_excellon_zeros_changed)
  5275. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5276. self.on_excellon_units_changed)
  5277. else:
  5278. # disconnect the signals
  5279. try:
  5280. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5281. disconnect(self.on_excellon_format_changed)
  5282. except TypeError:
  5283. pass
  5284. try:
  5285. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5286. disconnect(self.on_excellon_format_changed)
  5287. except TypeError:
  5288. pass
  5289. try:
  5290. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5291. disconnect(self.on_excellon_format_changed)
  5292. except TypeError:
  5293. pass
  5294. try:
  5295. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5296. disconnect(self.on_excellon_format_changed)
  5297. except TypeError:
  5298. pass
  5299. try:
  5300. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5301. disconnect(self.on_excellon_zeros_changed)
  5302. except TypeError:
  5303. pass
  5304. try:
  5305. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5306. disconnect(self.on_excellon_zeros_changed)
  5307. except TypeError:
  5308. pass
  5309. def on_excellon_format_changed(self):
  5310. """
  5311. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5312. :return: None
  5313. """
  5314. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5315. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5316. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5317. )
  5318. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5319. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5320. )
  5321. else:
  5322. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5323. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5324. )
  5325. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5326. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5327. )
  5328. def on_excellon_zeros_changed(self):
  5329. """
  5330. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5331. :return: None
  5332. """
  5333. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5334. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5335. )
  5336. def on_excellon_units_changed(self):
  5337. """
  5338. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5339. :return: None
  5340. """
  5341. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5342. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5343. )
  5344. self.on_excellon_format_changed()
  5345. # Setting plot colors handlers
  5346. def on_pf_color_entry(self):
  5347. self.defaults['global_plot_fill'] = \
  5348. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5349. self.defaults['global_plot_fill'][7:9]
  5350. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5351. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5352. def on_pf_color_button(self):
  5353. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5354. c_dialog = QtWidgets.QColorDialog()
  5355. plot_fill_color = c_dialog.getColor(initial=current_color)
  5356. if plot_fill_color.isValid() is False:
  5357. return
  5358. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5359. "background-color:%s" % str(plot_fill_color.name()))
  5360. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5361. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5362. self.defaults['global_plot_fill'] = new_val
  5363. def on_pf_color_spinner(self):
  5364. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5365. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5366. self.defaults['global_plot_fill'] = \
  5367. self.defaults['global_plot_fill'][:7] + \
  5368. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5369. self.defaults['global_plot_line'] = \
  5370. self.defaults['global_plot_line'][:7] + \
  5371. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5372. def on_pf_color_slider(self):
  5373. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5374. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5375. def on_pl_color_entry(self):
  5376. self.defaults['global_plot_line'] = \
  5377. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5378. self.defaults['global_plot_line'][7:9]
  5379. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5380. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5381. def on_pl_color_button(self):
  5382. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5383. # print(current_color)
  5384. c_dialog = QtWidgets.QColorDialog()
  5385. plot_line_color = c_dialog.getColor(initial=current_color)
  5386. if plot_line_color.isValid() is False:
  5387. return
  5388. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5389. "background-color:%s" % str(plot_line_color.name()))
  5390. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5391. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5392. self.defaults['global_plot_line'] = new_val_line
  5393. # Setting selection colors (left - right) handlers
  5394. def on_sf_color_entry(self):
  5395. self.defaults['global_sel_fill'] = \
  5396. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5397. self.defaults['global_sel_fill'][7:9]
  5398. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5399. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5400. def on_sf_color_button(self):
  5401. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5402. c_dialog = QtWidgets.QColorDialog()
  5403. plot_fill_color = c_dialog.getColor(initial=current_color)
  5404. if plot_fill_color.isValid() is False:
  5405. return
  5406. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5407. "background-color:%s" % str(plot_fill_color.name()))
  5408. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5409. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5410. self.defaults['global_sel_fill'] = new_val
  5411. def on_sf_color_spinner(self):
  5412. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5413. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5414. self.defaults['global_sel_fill'] = \
  5415. self.defaults['global_sel_fill'][:7] + \
  5416. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5417. self.defaults['global_sel_line'] = \
  5418. self.defaults['global_sel_line'][:7] + \
  5419. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5420. def on_sf_color_slider(self):
  5421. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5422. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5423. def on_sl_color_entry(self):
  5424. self.defaults['global_sel_line'] = \
  5425. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5426. self.defaults['global_sel_line'][7:9]
  5427. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5428. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5429. def on_sl_color_button(self):
  5430. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5431. c_dialog = QtWidgets.QColorDialog()
  5432. plot_line_color = c_dialog.getColor(initial=current_color)
  5433. if plot_line_color.isValid() is False:
  5434. return
  5435. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5436. "background-color:%s" % str(plot_line_color.name()))
  5437. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5438. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5439. self.defaults['global_sel_line'] = new_val_line
  5440. # Setting selection colors (right - left) handlers
  5441. def on_alt_sf_color_entry(self):
  5442. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5443. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5444. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5445. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5446. def on_alt_sf_color_button(self):
  5447. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5448. c_dialog = QtWidgets.QColorDialog()
  5449. plot_fill_color = c_dialog.getColor(initial=current_color)
  5450. if plot_fill_color.isValid() is False:
  5451. return
  5452. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5453. "background-color:%s" % str(plot_fill_color.name()))
  5454. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5455. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5456. self.defaults['global_alt_sel_fill'] = new_val
  5457. def on_alt_sf_color_spinner(self):
  5458. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5459. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5460. self.defaults['global_alt_sel_fill'] = \
  5461. self.defaults['global_alt_sel_fill'][:7] + \
  5462. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5463. self.defaults['global_alt_sel_line'] = \
  5464. self.defaults['global_alt_sel_line'][:7] + \
  5465. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5466. def on_alt_sf_color_slider(self):
  5467. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5468. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5469. def on_alt_sl_color_entry(self):
  5470. self.defaults['global_alt_sel_line'] = \
  5471. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5472. self.defaults['global_alt_sel_line'][7:9]
  5473. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5474. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5475. def on_alt_sl_color_button(self):
  5476. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5477. c_dialog = QtWidgets.QColorDialog()
  5478. plot_line_color = c_dialog.getColor(initial=current_color)
  5479. if plot_line_color.isValid() is False:
  5480. return
  5481. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5482. "background-color:%s" % str(plot_line_color.name()))
  5483. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5484. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5485. self.defaults['global_alt_sel_line'] = new_val_line
  5486. # Setting Editor colors
  5487. def on_draw_color_entry(self):
  5488. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5489. .draw_color_entry.get_value()
  5490. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5491. "background-color:%s" % str(self.defaults['global_draw_color']))
  5492. def on_draw_color_button(self):
  5493. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5494. c_dialog = QtWidgets.QColorDialog()
  5495. draw_color = c_dialog.getColor(initial=current_color)
  5496. if draw_color.isValid() is False:
  5497. return
  5498. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5499. "background-color:%s" % str(draw_color.name()))
  5500. new_val = str(draw_color.name())
  5501. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5502. self.defaults['global_draw_color'] = new_val
  5503. def on_sel_draw_color_entry(self):
  5504. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5505. .sel_draw_color_entry.get_value()
  5506. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5507. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5508. def on_sel_draw_color_button(self):
  5509. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5510. c_dialog = QtWidgets.QColorDialog()
  5511. sel_draw_color = c_dialog.getColor(initial=current_color)
  5512. if sel_draw_color.isValid() is False:
  5513. return
  5514. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5515. "background-color:%s" % str(sel_draw_color.name()))
  5516. new_val_sel = str(sel_draw_color.name())
  5517. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5518. self.defaults['global_sel_draw_color'] = new_val_sel
  5519. def on_proj_color_entry(self):
  5520. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5521. .proj_color_entry.get_value()
  5522. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5523. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5524. def on_proj_color_button(self):
  5525. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5526. c_dialog = QtWidgets.QColorDialog()
  5527. proj_color = c_dialog.getColor(initial=current_color)
  5528. if proj_color.isValid() is False:
  5529. return
  5530. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5531. "background-color:%s" % str(proj_color.name()))
  5532. new_val_sel = str(proj_color.name())
  5533. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5534. self.defaults['global_proj_item_color'] = new_val_sel
  5535. def on_proj_color_dis_entry(self):
  5536. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5537. .proj_color_dis_entry.get_value()
  5538. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5539. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5540. def on_proj_color_dis_button(self):
  5541. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5542. c_dialog = QtWidgets.QColorDialog()
  5543. proj_color = c_dialog.getColor(initial=current_color)
  5544. if proj_color.isValid() is False:
  5545. return
  5546. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5547. "background-color:%s" % str(proj_color.name()))
  5548. new_val_sel = str(proj_color.name())
  5549. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5550. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5551. def on_annotation_fontcolor_entry(self):
  5552. self.defaults['cncjob_annotation_fontcolor'] = \
  5553. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5554. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5555. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5556. def on_annotation_fontcolor_button(self):
  5557. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5558. c_dialog = QtWidgets.QColorDialog()
  5559. annotation_color = c_dialog.getColor(initial=current_color)
  5560. if annotation_color.isValid() is False:
  5561. return
  5562. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5563. "background-color:%s" % str(annotation_color.name()))
  5564. new_val_sel = str(annotation_color.name())
  5565. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5566. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5567. def on_film_color_entry(self):
  5568. self.defaults['tools_film_color'] = \
  5569. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5570. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5571. "background-color:%s;"
  5572. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5573. )
  5574. def on_film_color_button(self):
  5575. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5576. c_dialog = QtWidgets.QColorDialog()
  5577. film_color = c_dialog.getColor(initial=current_color)
  5578. if film_color.isValid() is False:
  5579. return
  5580. # if new color is different then mark that the Preferences are changed
  5581. if film_color != current_color:
  5582. self.on_preferences_edited()
  5583. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5584. "background-color:%s;"
  5585. "border-color: dimgray" % str(film_color.name())
  5586. )
  5587. new_val_sel = str(film_color.name())
  5588. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5589. self.defaults['tools_film_color'] = new_val_sel
  5590. def on_qrcode_fill_color_entry(self):
  5591. self.defaults['tools_qrcode_fill_color'] = \
  5592. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5593. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5594. "background-color:%s;"
  5595. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5596. )
  5597. def on_qrcode_fill_color_button(self):
  5598. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5599. c_dialog = QtWidgets.QColorDialog()
  5600. fill_color = c_dialog.getColor(initial=current_color)
  5601. if fill_color.isValid() is False:
  5602. return
  5603. # if new color is different then mark that the Preferences are changed
  5604. if fill_color != current_color:
  5605. self.on_preferences_edited()
  5606. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5607. "background-color:%s;"
  5608. "border-color: dimgray" % str(fill_color.name())
  5609. )
  5610. new_val_sel = str(fill_color.name())
  5611. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5612. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5613. def on_qrcode_back_color_entry(self):
  5614. self.defaults['tools_qrcode_back_color'] = \
  5615. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5616. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5617. "background-color:%s;"
  5618. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5619. )
  5620. def on_qrcode_back_color_button(self):
  5621. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5622. c_dialog = QtWidgets.QColorDialog()
  5623. back_color = c_dialog.getColor(initial=current_color)
  5624. if back_color.isValid() is False:
  5625. return
  5626. # if new color is different then mark that the Preferences are changed
  5627. if back_color != current_color:
  5628. self.on_preferences_edited()
  5629. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5630. "background-color:%s;"
  5631. "border-color: dimgray" % str(back_color.name())
  5632. )
  5633. new_val_sel = str(back_color.name())
  5634. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5635. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5636. def on_splash_changed(self, state):
  5637. settings = QSettings("Open Source", "FlatCAM")
  5638. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5639. # This will write the setting to the platform specific storage.
  5640. del settings
  5641. def on_tab_rmb_click(self, checked):
  5642. self.ui.notebook.set_detachable(val=checked)
  5643. self.defaults["global_tabs_detachable"] = checked
  5644. self.ui.plot_tab_area.set_detachable(val=checked)
  5645. self.defaults["global_tabs_detachable"] = checked
  5646. def on_tab_setup_context_menu(self):
  5647. initial_checked = self.defaults["global_tabs_detachable"]
  5648. action_name = str(_("Detachable Tabs"))
  5649. action = QtWidgets.QAction(self)
  5650. action.setCheckable(True)
  5651. action.setText(action_name)
  5652. action.setChecked(initial_checked)
  5653. self.ui.notebook.tabBar.addAction(action)
  5654. self.ui.plot_tab_area.tabBar.addAction(action)
  5655. try:
  5656. action.triggered.disconnect()
  5657. except TypeError:
  5658. pass
  5659. action.triggered.connect(self.on_tab_rmb_click)
  5660. def on_deselect_all(self):
  5661. self.collection.set_all_inactive()
  5662. self.delete_selection_shape()
  5663. def on_workspace_modified(self):
  5664. # self.save_defaults(silent=True)
  5665. if self.is_legacy is True:
  5666. self.plotcanvas.delete_workspace()
  5667. self.defaults_read_form()
  5668. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5669. def on_workspace(self):
  5670. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5671. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5672. else:
  5673. self.plotcanvas.delete_workspace()
  5674. self.defaults_read_form()
  5675. # self.save_defaults(silent=True)
  5676. def on_workspace_toggle(self):
  5677. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5678. try:
  5679. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5680. except TypeError:
  5681. pass
  5682. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5683. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5684. self.on_workspace()
  5685. def on_layout(self, index=None, lay=None):
  5686. """
  5687. Set the toolbars layout (location)
  5688. :param index:
  5689. :param lay: type of layout to be set on the toolbard
  5690. :return: None
  5691. """
  5692. self.report_usage("on_layout()")
  5693. if lay:
  5694. current_layout = lay
  5695. else:
  5696. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5697. lay_settings = QSettings("Open Source", "FlatCAM")
  5698. lay_settings.setValue('layout', current_layout)
  5699. # This will write the setting to the platform specific storage.
  5700. del lay_settings
  5701. # first remove the toolbars:
  5702. try:
  5703. self.ui.removeToolBar(self.ui.toolbarfile)
  5704. self.ui.removeToolBar(self.ui.toolbargeo)
  5705. self.ui.removeToolBar(self.ui.toolbarview)
  5706. self.ui.removeToolBar(self.ui.toolbarshell)
  5707. self.ui.removeToolBar(self.ui.toolbartools)
  5708. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5709. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5710. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5711. self.ui.removeToolBar(self.ui.snap_toolbar)
  5712. self.ui.removeToolBar(self.ui.toolbarshell)
  5713. except Exception:
  5714. pass
  5715. if current_layout == 'standard':
  5716. # ## TOOLBAR INSTALLATION # ##
  5717. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5718. self.ui.toolbarfile.setObjectName('File_TB')
  5719. self.ui.addToolBar(self.ui.toolbarfile)
  5720. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5721. self.ui.toolbargeo.setObjectName('Edit_TB')
  5722. self.ui.addToolBar(self.ui.toolbargeo)
  5723. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5724. self.ui.toolbarview.setObjectName('View_TB')
  5725. self.ui.addToolBar(self.ui.toolbarview)
  5726. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5727. self.ui.toolbarshell.setObjectName('Shell_TB')
  5728. self.ui.addToolBar(self.ui.toolbarshell)
  5729. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5730. self.ui.toolbartools.setObjectName('Tools_TB')
  5731. self.ui.addToolBar(self.ui.toolbartools)
  5732. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5733. # self.ui.exc_edit_toolbar.setVisible(False)
  5734. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5735. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5736. self.ui.addToolBarBreak()
  5737. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5738. # self.ui.geo_edit_toolbar.setVisible(False)
  5739. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5740. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5741. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5742. # self.ui.grb_edit_toolbar.setVisible(False)
  5743. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5744. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5745. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5746. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5747. # self.ui.snap_toolbar.setMaximumHeight(30)
  5748. self.ui.addToolBar(self.ui.snap_toolbar)
  5749. self.ui.corner_snap_btn.setVisible(False)
  5750. self.ui.snap_magnet.setVisible(False)
  5751. elif current_layout == 'compact':
  5752. # ## TOOLBAR INSTALLATION # ##
  5753. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5754. self.ui.toolbarfile.setObjectName('File_TB')
  5755. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5756. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5757. self.ui.toolbargeo.setObjectName('Edit_TB')
  5758. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5759. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5760. self.ui.toolbarshell.setObjectName('Shell_TB')
  5761. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5762. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5763. self.ui.toolbartools.setObjectName('Tools_TB')
  5764. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5765. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5766. # self.ui.geo_edit_toolbar.setVisible(False)
  5767. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5768. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5769. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5770. self.ui.toolbarview.setObjectName('View_TB')
  5771. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5772. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5773. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5774. # self.ui.grb_edit_toolbar.setVisible(False)
  5775. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5776. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5777. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5778. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5779. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5780. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5781. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5782. self.ui.snap_toolbar.setMaximumHeight(30)
  5783. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5784. self.ui.corner_snap_btn.setVisible(True)
  5785. self.ui.snap_magnet.setVisible(True)
  5786. # add all the actions to the toolbars
  5787. self.ui.populate_toolbars()
  5788. # reconnect all the signals to the toolbar actions
  5789. self.connect_toolbar_signals()
  5790. self.ui.grid_snap_btn.setChecked(True)
  5791. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5792. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5793. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5794. self.ui.grid_gap_link_cb.setChecked(True)
  5795. def on_cursor_type(self, val):
  5796. """
  5797. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5798. :return: None
  5799. """
  5800. self.app_cursor.enabled = False
  5801. if val == 'small':
  5802. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5803. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5804. self.app_cursor = self.plotcanvas.new_cursor()
  5805. else:
  5806. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5807. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5808. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5809. if self.ui.grid_snap_btn.isChecked():
  5810. self.app_cursor.enabled = True
  5811. else:
  5812. self.app_cursor.enabled = False
  5813. def on_cnc_custom_parameters(self, signal_text):
  5814. if signal_text == 'Parameters':
  5815. return
  5816. else:
  5817. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5818. def on_save_button(self, save_to_file=True):
  5819. log.debug("App.on_save_button() --> Applying preferences to file.")
  5820. # Preferences saved, update flag
  5821. self.preferences_changed_flag = False
  5822. # Preferences save, update the color of the Preferences Tab text
  5823. for idx in range(self.ui.plot_tab_area.count()):
  5824. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5825. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5826. self.inform.emit('%s' % _("Preferences applied."))
  5827. if save_to_file:
  5828. self.save_defaults(silent=False)
  5829. # load the defaults so they are updated into the app
  5830. self.load_defaults(filename='current_defaults')
  5831. # Re-fresh project options
  5832. self.on_options_app2project()
  5833. settgs = QSettings("Open Source", "FlatCAM")
  5834. # save the notebook font size
  5835. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5836. settgs.setValue('notebook_font_size', fsize)
  5837. # save the axis font size
  5838. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5839. settgs.setValue('axis_font_size', g_fsize)
  5840. # save the textbox font size
  5841. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5842. settgs.setValue('textbox_font_size', tb_fsize)
  5843. settgs.setValue(
  5844. 'machinist',
  5845. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5846. )
  5847. # This will write the setting to the platform specific storage.
  5848. del settgs
  5849. def on_pref_close_button(self):
  5850. # Preferences saved, update flag
  5851. self.preferences_changed_flag = False
  5852. try:
  5853. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5854. except TypeError:
  5855. pass
  5856. self.defaults_write_form()
  5857. # Preferences save, update the color of the Preferences Tab text
  5858. for idx in range(self.ui.plot_tab_area.count()):
  5859. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5860. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5861. self.ui.plot_tab_area.closeTab(idx)
  5862. break
  5863. self.inform.emit('%s' % _("Preferences closed without saving."))
  5864. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5865. def on_tool_add_keypress(self):
  5866. # ## Current application units in Upper Case
  5867. self.units = self.defaults['units'].upper()
  5868. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5869. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5870. if notebook_widget_name == 'selected_tab':
  5871. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5872. # Tool add works for Geometry only if Advanced is True in Preferences
  5873. if self.defaults["global_app_level"] == 'a':
  5874. tool_add_popup = FCInputDialog(title="New Tool ...",
  5875. text='Enter a Tool Diameter:',
  5876. min=0.0000, max=99.9999, decimals=4)
  5877. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5878. val, ok = tool_add_popup.get_value()
  5879. if ok:
  5880. if float(val) == 0:
  5881. self.inform.emit('[WARNING_NOTCL] %s' %
  5882. _("Please enter a tool diameter with non-zero value, in Float format."))
  5883. return
  5884. self.collection.get_active().on_tool_add(dia=float(val))
  5885. else:
  5886. self.inform.emit('[WARNING_NOTCL] %s...' %
  5887. _("Adding Tool cancelled"))
  5888. else:
  5889. msgbox = QtWidgets.QMessageBox()
  5890. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5891. "Go to Preferences -> General - Show Advanced Options."))
  5892. msgbox.setWindowTitle("Tool adding ...")
  5893. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5894. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5895. msgbox.setDefaultButton(bt_ok)
  5896. msgbox.exec_()
  5897. # work only if the notebook tab on focus is the Tools_Tab
  5898. if notebook_widget_name == 'tool_tab':
  5899. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5900. # and only if the tool is NCC Tool
  5901. if tool_widget == self.ncclear_tool.toolName:
  5902. self.ncclear_tool.on_add_tool_by_key()
  5903. # and only if the tool is Paint Area Tool
  5904. elif tool_widget == self.paint_tool.toolName:
  5905. self.paint_tool.on_add_tool_by_key()
  5906. # and only if the tool is Solder Paste Dispensing Tool
  5907. elif tool_widget == self.paste_tool.toolName:
  5908. self.paste_tool.on_add_tool_by_key()
  5909. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5910. # See description bellow.
  5911. def on_delete_keypress(self):
  5912. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5913. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5914. if notebook_widget_name == 'selected_tab':
  5915. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5916. self.collection.get_active().on_tool_delete()
  5917. # work only if the notebook tab on focus is the Tools_Tab
  5918. elif notebook_widget_name == 'tool_tab':
  5919. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5920. # and only if the tool is NCC Tool
  5921. if tool_widget == self.ncclear_tool.toolName:
  5922. self.ncclear_tool.on_tool_delete()
  5923. # and only if the tool is Paint Tool
  5924. elif tool_widget == self.paint_tool.toolName:
  5925. self.paint_tool.on_tool_delete()
  5926. # and only if the tool is Solder Paste Dispensing Tool
  5927. elif tool_widget == self.paste_tool.toolName:
  5928. self.paste_tool.on_tool_delete()
  5929. else:
  5930. self.on_delete()
  5931. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5932. # some screens you have to be careful where you hover with your mouse.
  5933. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5934. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5935. # Complicated, I know :)
  5936. def on_delete(self):
  5937. """
  5938. Delete the currently selected FlatCAMObjs.
  5939. :return: None
  5940. """
  5941. self.report_usage("on_delete()")
  5942. response = None
  5943. bt_ok = None
  5944. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5945. # a geometry object before we update it.
  5946. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5947. and self.grb_editor.editor_active is False:
  5948. if self.defaults["global_delete_confirmation"] is True:
  5949. msgbox = QtWidgets.QMessageBox()
  5950. msgbox.setWindowTitle(_("Delete objects"))
  5951. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5952. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5953. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5954. "the selected objects?"))
  5955. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5956. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5957. msgbox.setDefaultButton(bt_ok)
  5958. msgbox.exec_()
  5959. response = msgbox.clickedButton()
  5960. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5961. if self.collection.get_active():
  5962. self.log.debug("App.on_delete()")
  5963. while self.collection.get_active():
  5964. obj_active = self.collection.get_active()
  5965. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5966. if isinstance(obj_active, FlatCAMGerber):
  5967. for el in obj_active.mark_shapes:
  5968. obj_active.mark_shapes[el].clear(update=True)
  5969. obj_active.mark_shapes[el].enabled = False
  5970. # obj_active.mark_shapes[el] = None
  5971. del el
  5972. elif isinstance(obj_active, FlatCAMCNCjob):
  5973. try:
  5974. obj_active.annotation.clear(update=True)
  5975. obj_active.annotation.enabled = False
  5976. except AttributeError:
  5977. pass
  5978. self.delete_first_selected()
  5979. self.inform.emit('%s...' %
  5980. _("Object(s) deleted"))
  5981. # make sure that the selection shape is deleted, too
  5982. self.delete_selection_shape()
  5983. else:
  5984. self.inform.emit(_("Failed. No object(s) selected..."))
  5985. else:
  5986. self.inform.emit(_("Save the work in Editor and try again ..."))
  5987. def delete_first_selected(self):
  5988. # Keep this for later
  5989. try:
  5990. sel_obj = self.collection.get_active()
  5991. name = sel_obj.options["name"]
  5992. isPlotted = sel_obj.options["plot"]
  5993. except AttributeError:
  5994. self.log.debug("Nothing selected for deletion")
  5995. return
  5996. if self.is_legacy is True:
  5997. # Remove plot only if the object was plotted otherwise delaxes will fail
  5998. if isPlotted:
  5999. try:
  6000. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  6001. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  6002. except Exception as e:
  6003. log.debug("App.delete_first_selected() --> %s" % str(e))
  6004. self.plotcanvas.auto_adjust_axes()
  6005. # Remove from dictionary
  6006. self.collection.delete_active()
  6007. # Clear form
  6008. self.setup_component_editor()
  6009. self.inform.emit('%s: %s' %
  6010. (_("Object deleted"), name))
  6011. def on_set_origin(self):
  6012. """
  6013. Set the origin to the left mouse click position
  6014. :return: None
  6015. """
  6016. # display the message for the user
  6017. # and ask him to click on the desired position
  6018. self.report_usage("on_set_origin()")
  6019. def origin_replot():
  6020. def worker_task():
  6021. with self.proc_container.new('%s...' % _("Plotting")):
  6022. for obj in self.collection.get_list():
  6023. obj.plot()
  6024. self.plotcanvas.fit_view()
  6025. if self.is_legacy:
  6026. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6027. else:
  6028. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6029. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6030. self.inform.emit(_('Click to set the origin ...'))
  6031. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6032. # first disconnect it as it may have been used by something else
  6033. try:
  6034. self.replot_signal.disconnect()
  6035. except TypeError:
  6036. pass
  6037. self.replot_signal[list].connect(origin_replot)
  6038. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6039. """
  6040. :param event:
  6041. :param location:
  6042. :param noplot:
  6043. :param use_thread:
  6044. :return:
  6045. """
  6046. noplot_sig = noplot
  6047. def worker_task():
  6048. with self.proc_container.new(_("Setting Origin...")):
  6049. for obj in self.collection.get_list():
  6050. obj.offset((x, y))
  6051. self.object_changed.emit(obj)
  6052. # Update the object bounding box options
  6053. a, b, c, d = obj.bounds()
  6054. obj.options['xmin'] = a
  6055. obj.options['ymin'] = b
  6056. obj.options['xmax'] = c
  6057. obj.options['ymax'] = d
  6058. self.inform.emit('[success] %s...' %
  6059. _('Origin set'))
  6060. if noplot_sig is False:
  6061. self.replot_signal.emit([])
  6062. if location is not None:
  6063. if len(location) != 2:
  6064. self.inform.emit('[ERROR_NOTCL] %s...' %
  6065. _("Origin coordinates specified but incomplete."))
  6066. return 'fail'
  6067. x, y = location
  6068. if use_thread is True:
  6069. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6070. else:
  6071. worker_task()
  6072. self.should_we_save = True
  6073. return
  6074. if event.button == 1:
  6075. if self.is_legacy is False:
  6076. event_pos = event.pos
  6077. else:
  6078. event_pos = (event.xdata, event.ydata)
  6079. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6080. if self.grid_status() == True:
  6081. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6082. else:
  6083. pos = pos_canvas
  6084. x = 0 - pos[0]
  6085. y = 0 - pos[1]
  6086. if use_thread is True:
  6087. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6088. else:
  6089. worker_task()
  6090. self.should_we_save = True
  6091. def on_jump_to(self, custom_location=None, fit_center=True):
  6092. """
  6093. Jump to a location by setting the mouse cursor location
  6094. :return:
  6095. """
  6096. self.report_usage("on_jump_to()")
  6097. # if self.is_legacy is True:
  6098. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6099. # return
  6100. if not custom_location:
  6101. dia_box_location = None
  6102. try:
  6103. dia_box_location = eval(self.clipboard.text())
  6104. except Exception:
  6105. pass
  6106. if type(dia_box_location) == tuple:
  6107. dia_box_location = str(dia_box_location)
  6108. else:
  6109. dia_box_location = None
  6110. dia_box = Dialog_box(title=_("Jump to ..."),
  6111. label=_("Enter the coordinates in format X,Y:"),
  6112. icon=QtGui.QIcon('share/jump_to16.png'),
  6113. initial_text=dia_box_location)
  6114. if dia_box.ok is True:
  6115. try:
  6116. location = eval(dia_box.location)
  6117. if not isinstance(location, tuple):
  6118. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6119. return
  6120. except Exception:
  6121. return
  6122. else:
  6123. return
  6124. else:
  6125. location = custom_location
  6126. units = self.defaults['units'].upper()
  6127. if fit_center:
  6128. self.plotcanvas.fit_center(loc=location)
  6129. cursor = QtGui.QCursor()
  6130. if self.is_legacy is False:
  6131. # I don't know where those differences come from but they are constant for the current
  6132. # execution of the application and they are multiples of a value around 0.0263mm.
  6133. # In a random way sometimes they are more sometimes they are less
  6134. # if units == 'MM':
  6135. # cal_factor = 0.0263
  6136. # else:
  6137. # cal_factor = 0.0263 / 25.4
  6138. cal_location = (location[0], location[1])
  6139. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6140. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6141. j_pos = (
  6142. int(canvas_origin.x() + round(jump_loc[0])),
  6143. int(canvas_origin.y() + round(jump_loc[1]))
  6144. )
  6145. cursor.setPos(j_pos[0], j_pos[1])
  6146. else:
  6147. # find the canvas origin which is in the top left corner
  6148. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6149. # determine the coordinates for the lowest left point of the canvas
  6150. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6151. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6152. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6153. # canvas) and the point (width, height) is in the top-right location
  6154. loc = self.plotcanvas.axes.transData.transform_point(location)
  6155. j_pos = (
  6156. int(x0 + loc[0]),
  6157. int(y0 - loc[1])
  6158. )
  6159. cursor.setPos(j_pos[0], j_pos[1])
  6160. self.plotcanvas.mouse = [location[0], location[1]]
  6161. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6162. if self.grid_status():
  6163. # Update cursor
  6164. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6165. symbol='++', edge_color=self.cursor_color_3D,
  6166. size=self.defaults["global_cursor_size"])
  6167. # Set the position label
  6168. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6169. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6170. # Set the relative position label
  6171. dx = location[0] - float(self.rel_point1[0])
  6172. dy = location[1] - float(self.rel_point1[1])
  6173. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6174. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6175. self.inform.emit('[success] %s' % _("Done."))
  6176. return location
  6177. def on_copy_object(self):
  6178. self.report_usage("on_copy_object()")
  6179. def initialize(obj_init, app):
  6180. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6181. try:
  6182. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6183. except AttributeError:
  6184. pass
  6185. try:
  6186. obj_init.apertures = deepcopy(obj.apertures)
  6187. except AttributeError:
  6188. pass
  6189. try:
  6190. if obj.tools:
  6191. obj_init.tools = deepcopy(obj.tools)
  6192. except Exception as e:
  6193. log.debug("App.on_copy_object() --> %s" % str(e))
  6194. try:
  6195. obj_init.source_file = deepcopy(obj.source_file)
  6196. except (AttributeError, TypeError):
  6197. pass
  6198. def initialize_excellon(obj_init, app):
  6199. obj_init.source_file = deepcopy(obj.source_file)
  6200. obj_init.tools = deepcopy(obj.tools)
  6201. # drills are offset, so they need to be deep copied
  6202. obj_init.drills = deepcopy(obj.drills)
  6203. # slots are offset, so they need to be deep copied
  6204. obj_init.slots = deepcopy(obj.slots)
  6205. obj_init.create_geometry()
  6206. def initialize_script(obj_init, app_obj):
  6207. obj_init.source_file = deepcopy(obj.source_file)
  6208. def initialize_document(obj_init, app_obj):
  6209. obj_init.source_file = deepcopy(obj.source_file)
  6210. for obj in self.collection.get_selected():
  6211. obj_name = obj.options["name"]
  6212. try:
  6213. if isinstance(obj, FlatCAMExcellon):
  6214. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6215. elif isinstance(obj, FlatCAMGerber):
  6216. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6217. elif isinstance(obj, FlatCAMGeometry):
  6218. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6219. elif isinstance(obj, FlatCAMScript):
  6220. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6221. elif isinstance(obj, FlatCAMDocument):
  6222. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6223. except Exception as e:
  6224. return "Operation failed: %s" % str(e)
  6225. def on_copy_object2(self, custom_name):
  6226. def initialize_geometry(obj_init, app):
  6227. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6228. try:
  6229. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6230. except AttributeError:
  6231. pass
  6232. try:
  6233. obj_init.apertures = deepcopy(obj.apertures)
  6234. except AttributeError:
  6235. pass
  6236. try:
  6237. if obj.tools:
  6238. obj_init.tools = deepcopy(obj.tools)
  6239. except Exception as ee:
  6240. log.debug("on_copy_object2() --> %s" % str(ee))
  6241. def initialize_gerber(obj_init, app):
  6242. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6243. obj_init.apertures = deepcopy(obj.apertures)
  6244. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6245. def initialize_excellon(obj_init, app):
  6246. obj_init.tools = deepcopy(obj.tools)
  6247. # drills are offset, so they need to be deep copied
  6248. obj_init.drills = deepcopy(obj.drills)
  6249. # slots are offset, so they need to be deep copied
  6250. obj_init.slots = deepcopy(obj.slots)
  6251. obj_init.create_geometry()
  6252. for obj in self.collection.get_selected():
  6253. obj_name = obj.options["name"]
  6254. try:
  6255. if isinstance(obj, FlatCAMExcellon):
  6256. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6257. elif isinstance(obj, FlatCAMGerber):
  6258. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6259. elif isinstance(obj, FlatCAMGeometry):
  6260. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6261. except Exception as e:
  6262. return "Operation failed: %s" % str(e)
  6263. def on_rename_object(self, text):
  6264. self.report_usage("on_rename_object()")
  6265. named_obj = self.collection.get_active()
  6266. for obj in named_obj:
  6267. if obj is list:
  6268. self.on_rename_object(text)
  6269. else:
  6270. try:
  6271. obj.options['name'] = text
  6272. except Exception as e:
  6273. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6274. def convert_any2geo(self):
  6275. self.report_usage("convert_any2geo()")
  6276. def initialize(obj_init, app):
  6277. obj_init.solid_geometry = obj.solid_geometry
  6278. try:
  6279. obj_init.follow_geometry = obj.follow_geometry
  6280. except AttributeError:
  6281. pass
  6282. try:
  6283. obj_init.apertures = obj.apertures
  6284. except AttributeError:
  6285. pass
  6286. try:
  6287. if obj.tools:
  6288. obj_init.tools = obj.tools
  6289. except AttributeError:
  6290. pass
  6291. def initialize_excellon(obj_init, app):
  6292. # objs = self.collection.get_selected()
  6293. # FlatCAMGeometry.merge(objs, obj)
  6294. solid_geo = []
  6295. for tool in obj.tools:
  6296. for geo in obj.tools[tool]['solid_geometry']:
  6297. solid_geo.append(geo)
  6298. obj_init.solid_geometry = deepcopy(solid_geo)
  6299. if not self.collection.get_selected():
  6300. log.warning("App.convert_any2geo --> No object selected")
  6301. self.inform.emit('[WARNING_NOTCL] %s' %
  6302. _("No object is selected. Select an object and try again."))
  6303. return
  6304. for obj in self.collection.get_selected():
  6305. obj_name = obj.options["name"]
  6306. try:
  6307. if isinstance(obj, FlatCAMExcellon):
  6308. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6309. else:
  6310. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6311. except Exception as e:
  6312. return "Operation failed: %s" % str(e)
  6313. def convert_any2gerber(self):
  6314. self.report_usage("convert_any2gerber()")
  6315. def initialize_geometry(obj_init, app):
  6316. apertures = {}
  6317. apid = 0
  6318. apertures[str(apid)] = {}
  6319. apertures[str(apid)]['geometry'] = []
  6320. for obj_orig in obj.solid_geometry:
  6321. new_elem = dict()
  6322. new_elem['solid'] = obj_orig
  6323. try:
  6324. new_elem['follow'] = obj_orig.exterior
  6325. except AttributeError:
  6326. pass
  6327. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6328. apertures[str(apid)]['size'] = 0.0
  6329. apertures[str(apid)]['type'] = 'C'
  6330. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6331. obj_init.apertures = deepcopy(apertures)
  6332. def initialize_excellon(obj_init, app):
  6333. apertures = {}
  6334. apid = 10
  6335. for tool in obj.tools:
  6336. apertures[str(apid)] = {}
  6337. apertures[str(apid)]['geometry'] = []
  6338. for geo in obj.tools[tool]['solid_geometry']:
  6339. new_el = dict()
  6340. new_el['solid'] = geo
  6341. new_el['follow'] = geo.exterior
  6342. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6343. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6344. apertures[str(apid)]['type'] = 'C'
  6345. apid += 1
  6346. # create solid_geometry
  6347. solid_geometry = []
  6348. for apid in apertures:
  6349. for geo_el in apertures[apid]['geometry']:
  6350. solid_geometry.append(geo_el['solid'])
  6351. solid_geometry = MultiPolygon(solid_geometry)
  6352. solid_geometry = solid_geometry.buffer(0.0000001)
  6353. obj_init.solid_geometry = deepcopy(solid_geometry)
  6354. obj_init.apertures = deepcopy(apertures)
  6355. # clear the working objects (perhaps not necessary due of Python GC)
  6356. apertures.clear()
  6357. if not self.collection.get_selected():
  6358. log.warning("App.convert_any2gerber --> No object selected")
  6359. self.inform.emit('[WARNING_NOTCL] %s' %
  6360. _("No object is selected. Select an object and try again."))
  6361. return
  6362. for obj in self.collection.get_selected():
  6363. obj_name = obj.options["name"]
  6364. try:
  6365. if isinstance(obj, FlatCAMExcellon):
  6366. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6367. elif isinstance(obj, FlatCAMGeometry):
  6368. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6369. else:
  6370. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6371. except Exception as e:
  6372. return "Operation failed: %s" % str(e)
  6373. def abort_all_tasks(self):
  6374. if self.abort_flag is False:
  6375. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6376. self.abort_flag = True
  6377. def app_is_idle(self):
  6378. if self.abort_flag:
  6379. self.inform.emit('[WARNING_NOTCL] %s' %
  6380. _("The current task was gracefully closed on user request..."))
  6381. self.abort_flag = False
  6382. def on_selectall(self):
  6383. self.report_usage("on_selectall()")
  6384. # delete the possible selection box around a possible selected object
  6385. self.delete_selection_shape()
  6386. for name in self.collection.get_names():
  6387. self.collection.set_active(name)
  6388. curr_sel_obj = self.collection.get_by_name(name)
  6389. # create the selection box around the selected object
  6390. if self.defaults['global_selection_shape'] is True:
  6391. self.draw_selection_shape(curr_sel_obj)
  6392. def on_preferences(self):
  6393. """
  6394. Adds the Preferences in a Tab in Plot Area
  6395. :return:
  6396. """
  6397. # add the tab if it was closed
  6398. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6399. # delete the absolute and relative position and messages in the infobar
  6400. self.ui.position_label.setText("")
  6401. self.ui.rel_position_label.setText("")
  6402. # Switch plot_area to preferences page
  6403. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6404. # self.ui.show()
  6405. # detect changes in the preferences
  6406. for idx in range(self.ui.pref_tab_area.count()):
  6407. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6408. try:
  6409. try:
  6410. tb.textEdited.disconnect(self.on_preferences_edited)
  6411. except (TypeError, AttributeError):
  6412. pass
  6413. tb.textEdited.connect(self.on_preferences_edited)
  6414. except AttributeError:
  6415. pass
  6416. try:
  6417. try:
  6418. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6419. except (TypeError, AttributeError):
  6420. pass
  6421. tb.modificationChanged.connect(self.on_preferences_edited)
  6422. except AttributeError:
  6423. pass
  6424. try:
  6425. try:
  6426. tb.toggled.disconnect(self.on_preferences_edited)
  6427. except (TypeError, AttributeError):
  6428. pass
  6429. tb.toggled.connect(self.on_preferences_edited)
  6430. except AttributeError:
  6431. pass
  6432. try:
  6433. try:
  6434. tb.valueChanged.disconnect(self.on_preferences_edited)
  6435. except (TypeError, AttributeError):
  6436. pass
  6437. tb.valueChanged.connect(self.on_preferences_edited)
  6438. except AttributeError:
  6439. pass
  6440. try:
  6441. try:
  6442. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6443. except (TypeError, AttributeError):
  6444. pass
  6445. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6446. except AttributeError:
  6447. pass
  6448. def on_preferences_edited(self):
  6449. self.inform.emit('[WARNING_NOTCL] %s' %
  6450. _("Preferences edited but not saved."))
  6451. for idx in range(self.ui.plot_tab_area.count()):
  6452. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6453. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6454. self.preferences_changed_flag = True
  6455. def on_tools_database(self):
  6456. """
  6457. Adds the Tools Database in a Tab in Plot Area
  6458. :return:
  6459. """
  6460. for idx in range(self.ui.plot_tab_area.count()):
  6461. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6462. # there can be only one instance of Tools Database at one time
  6463. return
  6464. self.tools_db_tab = ToolsDB(
  6465. app=self,
  6466. parent=self.ui,
  6467. callback_on_edited=self.on_tools_db_edited,
  6468. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6469. )
  6470. # add the tab if it was closed
  6471. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6472. self.tools_db_tab.setObjectName("database_tab")
  6473. # delete the absolute and relative position and messages in the infobar
  6474. self.ui.position_label.setText("")
  6475. self.ui.rel_position_label.setText("")
  6476. # Switch plot_area to preferences page
  6477. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6478. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6479. self.tools_db_tab.ui_connect()
  6480. def on_tools_db_edited(self):
  6481. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6482. for idx in range(self.ui.plot_tab_area.count()):
  6483. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6484. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6485. self.tools_db_changed_flag = True
  6486. def on_geometry_tool_add_from_db_executed(self, tool):
  6487. """
  6488. Here add the tool from DB in the selected geometry object
  6489. :return:
  6490. """
  6491. tool_from_db = deepcopy(tool)
  6492. obj = self.collection.get_active()
  6493. if isinstance(obj, FlatCAMGeometry):
  6494. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6495. for idx in range(self.ui.plot_tab_area.count()):
  6496. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6497. wdg = self.ui.plot_tab_area.widget(idx)
  6498. wdg.deleteLater()
  6499. self.ui.plot_tab_area.removeTab(idx)
  6500. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6501. else:
  6502. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6503. def on_plot_area_tab_closed(self, title):
  6504. if title == _("Preferences"):
  6505. # disconnect
  6506. for idx in range(self.ui.pref_tab_area.count()):
  6507. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6508. try:
  6509. tb.textEdited.disconnect(self.on_preferences_edited)
  6510. except (TypeError, AttributeError):
  6511. pass
  6512. try:
  6513. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6514. except (TypeError, AttributeError):
  6515. pass
  6516. try:
  6517. tb.toggled.disconnect(self.on_preferences_edited)
  6518. except (TypeError, AttributeError):
  6519. pass
  6520. try:
  6521. tb.valueChanged.disconnect(self.on_preferences_edited)
  6522. except (TypeError, AttributeError):
  6523. pass
  6524. try:
  6525. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6526. except (TypeError, AttributeError):
  6527. pass
  6528. if self.preferences_changed_flag is True:
  6529. msgbox = QtWidgets.QMessageBox()
  6530. msgbox.setText(_("One or more values are changed.\n"
  6531. "Do you want to save the Preferences?"))
  6532. msgbox.setWindowTitle(_("Save Preferences"))
  6533. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6534. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6535. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6536. msgbox.setDefaultButton(bt_yes)
  6537. msgbox.exec_()
  6538. response = msgbox.clickedButton()
  6539. if response == bt_yes:
  6540. self.on_save_button(save_to_file=True)
  6541. self.inform.emit('[success] %s' % _("Preferences saved."))
  6542. else:
  6543. self.preferences_changed_flag = False
  6544. self.inform.emit('')
  6545. return
  6546. if title == _("Tools Database"):
  6547. # disconnect the signals from the table widget in tab
  6548. self.tools_db_tab.ui_disconnect()
  6549. if self.tools_db_changed_flag is True:
  6550. msgbox = QtWidgets.QMessageBox()
  6551. msgbox.setText(_("One or more Tools are edited.\n"
  6552. "Do you want to update the Tools Database?"))
  6553. msgbox.setWindowTitle(_("Save Tools Database"))
  6554. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6555. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6556. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6557. msgbox.setDefaultButton(bt_yes)
  6558. msgbox.exec_()
  6559. response = msgbox.clickedButton()
  6560. if response == bt_yes:
  6561. self.tools_db_tab.on_save_tools_db()
  6562. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6563. else:
  6564. self.tools_db_changed_flag = False
  6565. self.inform.emit('')
  6566. return
  6567. self.tools_db_tab.deleteLater()
  6568. if title == _("Code Editor"):
  6569. self.toggle_codeeditor = False
  6570. if title == _("Bookmarks Manager"):
  6571. self.book_dialog_tab.rebuild_actions()
  6572. self.book_dialog_tab.deleteLater()
  6573. def on_flipy(self):
  6574. self.report_usage("on_flipy()")
  6575. obj_list = self.collection.get_selected()
  6576. xminlist = []
  6577. yminlist = []
  6578. xmaxlist = []
  6579. ymaxlist = []
  6580. if not obj_list:
  6581. self.inform.emit('[WARNING_NOTCL] %s' %
  6582. _("No object selected to Flip on Y axis."))
  6583. else:
  6584. try:
  6585. # first get a bounding box to fit all
  6586. for obj in obj_list:
  6587. xmin, ymin, xmax, ymax = obj.bounds()
  6588. xminlist.append(xmin)
  6589. yminlist.append(ymin)
  6590. xmaxlist.append(xmax)
  6591. ymaxlist.append(ymax)
  6592. # get the minimum x,y and maximum x,y for all objects selected
  6593. xminimal = min(xminlist)
  6594. yminimal = min(yminlist)
  6595. xmaximal = max(xmaxlist)
  6596. ymaximal = max(ymaxlist)
  6597. px = 0.5 * (xminimal + xmaximal)
  6598. py = 0.5 * (yminimal + ymaximal)
  6599. # execute mirroring
  6600. for obj in obj_list:
  6601. obj.mirror('X', [px, py])
  6602. obj.plot()
  6603. self.object_changed.emit(obj)
  6604. self.inform.emit('[success] %s' %
  6605. _("Flip on Y axis done."))
  6606. except Exception as e:
  6607. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6608. return
  6609. def on_flipx(self):
  6610. self.report_usage("on_flipx()")
  6611. obj_list = self.collection.get_selected()
  6612. xminlist = []
  6613. yminlist = []
  6614. xmaxlist = []
  6615. ymaxlist = []
  6616. if not obj_list:
  6617. self.inform.emit('[WARNING_NOTCL] %s' %
  6618. _("No object selected to Flip on X axis."))
  6619. else:
  6620. try:
  6621. # first get a bounding box to fit all
  6622. for obj in obj_list:
  6623. xmin, ymin, xmax, ymax = obj.bounds()
  6624. xminlist.append(xmin)
  6625. yminlist.append(ymin)
  6626. xmaxlist.append(xmax)
  6627. ymaxlist.append(ymax)
  6628. # get the minimum x,y and maximum x,y for all objects selected
  6629. xminimal = min(xminlist)
  6630. yminimal = min(yminlist)
  6631. xmaximal = max(xmaxlist)
  6632. ymaximal = max(ymaxlist)
  6633. px = 0.5 * (xminimal + xmaximal)
  6634. py = 0.5 * (yminimal + ymaximal)
  6635. # execute mirroring
  6636. for obj in obj_list:
  6637. obj.mirror('Y', [px, py])
  6638. obj.plot()
  6639. self.object_changed.emit(obj)
  6640. self.inform.emit('[success] %s' %
  6641. _("Flip on X axis done."))
  6642. except Exception as e:
  6643. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6644. return
  6645. def on_rotate(self, silent=False, preset=None):
  6646. self.report_usage("on_rotate()")
  6647. obj_list = self.collection.get_selected()
  6648. xminlist = []
  6649. yminlist = []
  6650. xmaxlist = []
  6651. ymaxlist = []
  6652. if not obj_list:
  6653. self.inform.emit('[WARNING_NOTCL] %s' %
  6654. _("No object selected to Rotate."))
  6655. else:
  6656. if silent is False:
  6657. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6658. min=-360, max=360, decimals=4,
  6659. init_val=float(self.defaults['tools_transform_rotate']))
  6660. num, ok = rotatebox.get_value()
  6661. else:
  6662. num = preset
  6663. ok = True
  6664. if ok:
  6665. try:
  6666. # first get a bounding box to fit all
  6667. for obj in obj_list:
  6668. xmin, ymin, xmax, ymax = obj.bounds()
  6669. xminlist.append(xmin)
  6670. yminlist.append(ymin)
  6671. xmaxlist.append(xmax)
  6672. ymaxlist.append(ymax)
  6673. # get the minimum x,y and maximum x,y for all objects selected
  6674. xminimal = min(xminlist)
  6675. yminimal = min(yminlist)
  6676. xmaximal = max(xmaxlist)
  6677. ymaximal = max(ymaxlist)
  6678. px = 0.5 * (xminimal + xmaximal)
  6679. py = 0.5 * (yminimal + ymaximal)
  6680. for sel_obj in obj_list:
  6681. sel_obj.rotate(-float(num), point=(px, py))
  6682. sel_obj.plot()
  6683. self.object_changed.emit(sel_obj)
  6684. self.inform.emit('[success] %s' %
  6685. _("Rotation done."))
  6686. except Exception as e:
  6687. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6688. return
  6689. def on_skewx(self):
  6690. self.report_usage("on_skewx()")
  6691. obj_list = self.collection.get_selected()
  6692. xminlist = []
  6693. yminlist = []
  6694. if not obj_list:
  6695. self.inform.emit('[WARNING_NOTCL] %s' %
  6696. _("No object selected to Skew/Shear on X axis."))
  6697. else:
  6698. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6699. min=-360, max=360, decimals=4,
  6700. init_val=float(self.defaults['tools_transform_skew_x']))
  6701. num, ok = skewxbox.get_value()
  6702. if ok:
  6703. # first get a bounding box to fit all
  6704. for obj in obj_list:
  6705. xmin, ymin, xmax, ymax = obj.bounds()
  6706. xminlist.append(xmin)
  6707. yminlist.append(ymin)
  6708. # get the minimum x,y and maximum x,y for all objects selected
  6709. xminimal = min(xminlist)
  6710. yminimal = min(yminlist)
  6711. for obj in obj_list:
  6712. obj.skew(num, 0, point=(xminimal, yminimal))
  6713. obj.plot()
  6714. self.object_changed.emit(obj)
  6715. self.inform.emit('[success] %s' %
  6716. _("Skew on X axis done."))
  6717. def on_skewy(self):
  6718. self.report_usage("on_skewy()")
  6719. obj_list = self.collection.get_selected()
  6720. xminlist = []
  6721. yminlist = []
  6722. if not obj_list:
  6723. self.inform.emit('[WARNING_NOTCL] %s' %
  6724. _("No object selected to Skew/Shear on Y axis."))
  6725. else:
  6726. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6727. min=-360, max=360, decimals=4,
  6728. init_val=float(self.defaults['tools_transform_skew_y']))
  6729. num, ok = skewybox.get_value()
  6730. if ok:
  6731. # first get a bounding box to fit all
  6732. for obj in obj_list:
  6733. xmin, ymin, xmax, ymax = obj.bounds()
  6734. xminlist.append(xmin)
  6735. yminlist.append(ymin)
  6736. # get the minimum x,y and maximum x,y for all objects selected
  6737. xminimal = min(xminlist)
  6738. yminimal = min(yminlist)
  6739. for obj in obj_list:
  6740. obj.skew(0, num, point=(xminimal, yminimal))
  6741. obj.plot()
  6742. self.object_changed.emit(obj)
  6743. self.inform.emit('[success] %s' %
  6744. _("Skew on Y axis done."))
  6745. def on_plots_updated(self):
  6746. """
  6747. Callback used to report when the plots have changed.
  6748. Adjust axes and zooms to fit.
  6749. :return: None
  6750. """
  6751. if self.is_legacy is False:
  6752. self.plotcanvas.update() # TODO: Need update canvas?
  6753. else:
  6754. self.plotcanvas.auto_adjust_axes()
  6755. self.on_zoom_fit(None)
  6756. self.collection.update_view()
  6757. # self.inform.emit(_("Plots updated ..."))
  6758. # TODO: Rework toolbar 'clear', 'replot' functions
  6759. def on_toolbar_replot(self):
  6760. """
  6761. Callback for toolbar button. Re-plots all objects.
  6762. :return: None
  6763. """
  6764. self.report_usage("on_toolbar_replot")
  6765. self.log.debug("on_toolbar_replot()")
  6766. try:
  6767. self.collection.get_active().read_form()
  6768. except AttributeError:
  6769. self.log.debug("on_toolbar_replot(): AttributeError")
  6770. pass
  6771. self.plot_all()
  6772. def on_row_activated(self, index):
  6773. if index.isValid():
  6774. if index.internalPointer().parent_item != self.collection.root_item:
  6775. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6776. self.collection.on_item_activated(index)
  6777. def on_row_selected(self, obj_name):
  6778. # this is a special string; when received it will make all entries unchecked
  6779. # it mean we clicked outside of the items and deselected all
  6780. if obj_name == 'none':
  6781. for act in self.ui.menuobjects.actions():
  6782. act.setChecked(False)
  6783. return
  6784. # get the name of the selected objects and add them to a list
  6785. name_list = list()
  6786. for obj in self.collection.get_selected():
  6787. name_list.append(obj.options['name'])
  6788. # set all actions as unchecked but the ones selected make them checked
  6789. for act in self.ui.menuobjects.actions():
  6790. act.setChecked(False)
  6791. if act.text() in name_list:
  6792. act.setChecked(True)
  6793. def on_collection_updated(self, obj, state, old_name):
  6794. """
  6795. Create a menu from the object loaded in the collection.
  6796. TODO: should use the collection model to do this
  6797. :param obj: object that was changd (added, deleted, renamed)
  6798. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6799. :param old_name: the old name of the object before the action that triggered this slot happened
  6800. :return: None
  6801. """
  6802. icon_files = {
  6803. "gerber": "share/flatcam_icon16.png",
  6804. "excellon": "share/drill16.png",
  6805. "cncjob": "share/cnc16.png",
  6806. "geometry": "share/geometry16.png",
  6807. "script": "share/script_new16.png",
  6808. "document": "share/notes16_1.png"
  6809. }
  6810. if state == 'append':
  6811. for act in self.ui.menuobjects.actions():
  6812. try:
  6813. act.triggered.disconnect()
  6814. except TypeError:
  6815. pass
  6816. self.ui.menuobjects.clear()
  6817. gerber_list = list()
  6818. exc_list = list()
  6819. cncjob_list = list()
  6820. geo_list = list()
  6821. script_list = list()
  6822. doc_list = list()
  6823. for name in self.collection.get_names():
  6824. obj_named = self.collection.get_by_name(name)
  6825. if obj_named.kind == 'gerber':
  6826. gerber_list.append(name)
  6827. elif obj_named.kind == 'excellon':
  6828. exc_list.append(name)
  6829. elif obj_named.kind == 'cncjob':
  6830. cncjob_list.append(name)
  6831. elif obj_named.kind == 'geometry':
  6832. geo_list.append(name)
  6833. elif obj_named.kind == 'script':
  6834. script_list.append(name)
  6835. elif obj_named.kind == 'document':
  6836. doc_list.append(name)
  6837. def add_act(o_name):
  6838. obj_for_icon = self.collection.get_by_name(o_name)
  6839. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6840. add_action.setCheckable(True)
  6841. add_action.setText(o_name)
  6842. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6843. add_action.triggered.connect(
  6844. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6845. self.collection.set_inactive(o_name))
  6846. self.ui.menuobjects.addAction(add_action)
  6847. for name in gerber_list:
  6848. add_act(name)
  6849. self.ui.menuobjects.addSeparator()
  6850. for name in exc_list:
  6851. add_act(name)
  6852. self.ui.menuobjects.addSeparator()
  6853. for name in cncjob_list:
  6854. add_act(name)
  6855. self.ui.menuobjects.addSeparator()
  6856. for name in geo_list:
  6857. add_act(name)
  6858. self.ui.menuobjects.addSeparator()
  6859. for name in script_list:
  6860. add_act(name)
  6861. self.ui.menuobjects.addSeparator()
  6862. for name in doc_list:
  6863. add_act(name)
  6864. self.ui.menuobjects.addSeparator()
  6865. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6866. QtGui.QIcon('share/select_all.png'),
  6867. _('Select All')
  6868. )
  6869. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6870. QtGui.QIcon('share/deselect_all32.png'),
  6871. _('Deselect All')
  6872. )
  6873. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6874. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6875. elif state == 'delete':
  6876. for act in self.ui.menuobjects.actions():
  6877. if act.text() == obj.options['name']:
  6878. try:
  6879. act.triggered.disconnect()
  6880. except TypeError:
  6881. pass
  6882. self.ui.menuobjects.removeAction(act)
  6883. break
  6884. elif state == 'rename':
  6885. for act in self.ui.menuobjects.actions():
  6886. if act.text() == old_name:
  6887. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6888. add_action.setText(obj.options['name'])
  6889. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6890. add_action.triggered.connect(
  6891. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6892. self.collection.set_inactive(obj.options['name']))
  6893. self.ui.menuobjects.insertAction(act, add_action)
  6894. try:
  6895. act.triggered.disconnect()
  6896. except TypeError:
  6897. pass
  6898. self.ui.menuobjects.removeAction(act)
  6899. break
  6900. elif state == 'delete_all':
  6901. for act in self.ui.menuobjects.actions():
  6902. try:
  6903. act.triggered.disconnect()
  6904. except TypeError:
  6905. pass
  6906. self.ui.menuobjects.clear()
  6907. self.ui.menuobjects.addSeparator()
  6908. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6909. QtGui.QIcon('share/select_all.png'),
  6910. _('Select All')
  6911. )
  6912. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6913. QtGui.QIcon('share/deselect_all32.png'),
  6914. _('Deselect All')
  6915. )
  6916. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6917. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6918. def on_objects_selection(self, on_off):
  6919. obj_list = self.collection.get_names()
  6920. if on_off is True:
  6921. self.collection.set_all_active()
  6922. for act in self.ui.menuobjects.actions():
  6923. try:
  6924. act.setChecked(True)
  6925. except Exception:
  6926. pass
  6927. if obj_list:
  6928. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6929. else:
  6930. self.collection.set_all_inactive()
  6931. for act in self.ui.menuobjects.actions():
  6932. try:
  6933. act.setChecked(False)
  6934. except Exception:
  6935. pass
  6936. if obj_list:
  6937. self.inform.emit('%s' % _("Objects selection is cleared."))
  6938. else:
  6939. self.inform.emit('')
  6940. def grid_status(self):
  6941. if self.ui.grid_snap_btn.isChecked():
  6942. return True
  6943. else:
  6944. return False
  6945. def populate_cmenu_grids(self):
  6946. units = self.defaults['units'].lower()
  6947. self.ui.cmenu_gridmenu.clear()
  6948. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6949. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6950. grid_toggle.setCheckable(True)
  6951. if self.grid_status() == True:
  6952. grid_toggle.setChecked(True)
  6953. else:
  6954. grid_toggle.setChecked(False)
  6955. self.ui.cmenu_gridmenu.addSeparator()
  6956. for grid in sorted_list:
  6957. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6958. action.triggered.connect(self.set_grid)
  6959. self.ui.cmenu_gridmenu.addSeparator()
  6960. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6961. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6962. grid_add.triggered.connect(self.on_grid_add)
  6963. grid_delete.triggered.connect(self.on_grid_delete)
  6964. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6965. def set_grid(self):
  6966. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6967. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6968. def on_grid_add(self):
  6969. # ## Current application units in lower Case
  6970. units = self.defaults['units'].lower()
  6971. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6972. text=_('Enter a Grid Value:'),
  6973. min=0.0000, max=99.9999, decimals=4)
  6974. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6975. val, ok = grid_add_popup.get_value()
  6976. if ok:
  6977. if float(val) == 0:
  6978. self.inform.emit('[WARNING_NOTCL] %s' %
  6979. _("Please enter a grid value with non-zero value, in Float format."))
  6980. return
  6981. else:
  6982. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6983. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6984. self.inform.emit('[success] %s...' %
  6985. _("New Grid added"))
  6986. else:
  6987. self.inform.emit('[WARNING_NOTCL] %s...' %
  6988. _("Grid already exists"))
  6989. else:
  6990. self.inform.emit('[WARNING_NOTCL] %s...' %
  6991. _("Adding New Grid cancelled"))
  6992. def on_grid_delete(self):
  6993. # ## Current application units in lower Case
  6994. units = self.defaults['units'].lower()
  6995. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6996. text='Enter a Grid Value:',
  6997. min=0.0000, max=99.9999, decimals=4)
  6998. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6999. val, ok = grid_del_popup.get_value()
  7000. if ok:
  7001. if float(val) == 0:
  7002. self.inform.emit('[WARNING_NOTCL] %s' %
  7003. _("Please enter a grid value with non-zero value, in Float format."))
  7004. return
  7005. else:
  7006. try:
  7007. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7008. except ValueError:
  7009. self.inform.emit('[ERROR_NOTCL]%s...' %
  7010. _(" Grid Value does not exist"))
  7011. return
  7012. self.inform.emit('[success] %s...' %
  7013. _("Grid Value deleted"))
  7014. else:
  7015. self.inform.emit('[WARNING_NOTCL] %s...' %
  7016. _("Delete Grid value cancelled"))
  7017. def on_shortcut_list(self):
  7018. self.report_usage("on_shortcut_list()")
  7019. # add the tab if it was closed
  7020. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7021. # delete the absolute and relative position and messages in the infobar
  7022. self.ui.position_label.setText("")
  7023. self.ui.rel_position_label.setText("")
  7024. # Switch plot_area to preferences page
  7025. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7026. # self.ui.show()
  7027. def on_select_tab(self, name):
  7028. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7029. if self.ui.splitter.sizes()[0] == 0:
  7030. self.ui.splitter.setSizes([1, 1])
  7031. else:
  7032. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7033. self.ui.splitter.setSizes([0, 1])
  7034. if name == 'project':
  7035. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7036. elif name == 'selected':
  7037. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7038. elif name == 'tool':
  7039. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7040. def on_copy_name(self):
  7041. self.report_usage("on_copy_name()")
  7042. obj = self.collection.get_active()
  7043. try:
  7044. name = obj.options["name"]
  7045. except AttributeError:
  7046. log.debug("on_copy_name() --> No object selected to copy it's name")
  7047. self.inform.emit('[WARNING_NOTCL]%s' %
  7048. _(" No object selected to copy it's name"))
  7049. return
  7050. self.clipboard.setText(name)
  7051. self.inform.emit(_("Name copied on clipboard ..."))
  7052. def on_mouse_click_over_plot(self, event):
  7053. """
  7054. Default actions are:
  7055. :param event: Contains information about the event, like which button
  7056. was clicked, the pixel coordinates and the axes coordinates.
  7057. :return: None
  7058. """
  7059. self.pos = list()
  7060. if self.is_legacy is False:
  7061. event_pos = event.pos
  7062. pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7063. # Set the mouse button for panning
  7064. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7065. else:
  7066. event_pos = (event.xdata, event.ydata)
  7067. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7068. pan_button = 3 if self.defaults["global_pan_button"] == '2'else 2
  7069. # So it can receive key presses
  7070. self.plotcanvas.native.setFocus()
  7071. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7072. if self.grid_status() == True:
  7073. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7074. else:
  7075. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7076. try:
  7077. if event.button == 1:
  7078. # Reset here the relative coordinates so there is a new reference on the click position
  7079. if self.rel_point1 is None:
  7080. self.rel_point1 = self.pos
  7081. else:
  7082. self.rel_point2 = copy(self.rel_point1)
  7083. self.rel_point1 = self.pos
  7084. self.on_mouse_move_over_plot(event, origin_click=True)
  7085. except Exception as e:
  7086. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7087. def on_mouse_double_click_over_plot(self, event):
  7088. if event.button == 1:
  7089. self.doubleclick = True
  7090. def on_mouse_move_over_plot(self, event, origin_click=None):
  7091. """
  7092. Callback for the mouse motion event over the plot.
  7093. :param event: Contains information about the event.
  7094. :param origin_click
  7095. :return: None
  7096. """
  7097. if self.is_legacy is False:
  7098. event_pos = event.pos
  7099. if self.defaults["global_pan_button"] == '2':
  7100. pan_button = 2
  7101. else:
  7102. pan_button = 3
  7103. self.event_is_dragging = event.is_dragging
  7104. else:
  7105. event_pos = (event.xdata, event.ydata)
  7106. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7107. if self.defaults["global_pan_button"] == '2':
  7108. pan_button = 3
  7109. else:
  7110. pan_button = 2
  7111. self.event_is_dragging = self.plotcanvas.is_dragging
  7112. # So it can receive key presses
  7113. self.plotcanvas.native.setFocus()
  7114. self.pos_jump = event_pos
  7115. self.ui.popMenu.mouse_is_panning = False
  7116. if not origin_click:
  7117. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7118. if event.button == pan_button and self.event_is_dragging == 1:
  7119. self.ui.popMenu.mouse_is_panning = True
  7120. return
  7121. if self.rel_point1 is not None:
  7122. try: # May fail in case mouse not within axes
  7123. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7124. if self.grid_status() == True:
  7125. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7126. # Update cursor
  7127. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7128. symbol='++', edge_color=self.cursor_color_3D,
  7129. size=self.defaults["global_cursor_size"])
  7130. else:
  7131. pos = (pos_canvas[0], pos_canvas[1])
  7132. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7133. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7134. dx = pos[0] - float(self.rel_point1[0])
  7135. dy = pos[1] - float(self.rel_point1[1])
  7136. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7137. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7138. self.mouse = [pos[0], pos[1]]
  7139. # if the mouse is moved and the LMB is clicked then the action is a selection
  7140. if self.event_is_dragging == 1 and event.button == 1:
  7141. self.delete_selection_shape()
  7142. if dx < 0:
  7143. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7144. face_color=self.defaults['global_alt_sel_fill'])
  7145. self.selection_type = False
  7146. elif dx > 0:
  7147. self.draw_moving_selection_shape(self.pos, pos)
  7148. self.selection_type = True
  7149. else:
  7150. self.selection_type = None
  7151. # hover effect - enabled in Preferences -> General -> GUI Settings
  7152. if self.defaults['global_hover']:
  7153. for obj in self.collection.get_list():
  7154. try:
  7155. # select the object(s) only if it is enabled (plotted)
  7156. if obj.options['plot']:
  7157. if obj not in self.collection.get_selected():
  7158. poly_obj = Polygon(
  7159. [(obj.options['xmin'], obj.options['ymin']),
  7160. (obj.options['xmax'], obj.options['ymin']),
  7161. (obj.options['xmax'], obj.options['ymax']),
  7162. (obj.options['xmin'], obj.options['ymax'])]
  7163. )
  7164. if Point(pos).within(poly_obj):
  7165. if obj.isHovering is False:
  7166. obj.isHovering = True
  7167. obj.notHovering = True
  7168. # create the selection box around the selected object
  7169. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7170. else:
  7171. if obj.notHovering is True:
  7172. obj.notHovering = False
  7173. obj.isHovering = False
  7174. self.delete_hover_shape()
  7175. except Exception:
  7176. # the Exception here will happen if we try to select on screen and we have an
  7177. # newly (and empty) just created Geometry or Excellon object that do not have the
  7178. # xmin, xmax, ymin, ymax options.
  7179. # In this case poly_obj creation (see above) will fail
  7180. pass
  7181. except Exception:
  7182. self.ui.position_label.setText("")
  7183. self.ui.rel_position_label.setText("")
  7184. self.mouse = None
  7185. def on_mouse_click_release_over_plot(self, event):
  7186. """
  7187. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7188. and has been registered in ''self.__init__()''.
  7189. :param event: contains information about the event.
  7190. :return:
  7191. """
  7192. if self.is_legacy is False:
  7193. event_pos = event.pos
  7194. right_button = 2
  7195. else:
  7196. event_pos = (event.xdata, event.ydata)
  7197. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7198. right_button = 3
  7199. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7200. if self.grid_status() == True:
  7201. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7202. else:
  7203. pos = (pos_canvas[0], pos_canvas[1])
  7204. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7205. # canvas menu
  7206. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7207. self.cursor = QtGui.QCursor()
  7208. self.populate_cmenu_grids()
  7209. self.ui.popMenu.popup(self.cursor.pos())
  7210. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7211. # selection and then select a type of selection ("enclosing" or "touching")
  7212. if event.button == 1: # left click
  7213. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7214. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7215. if modifiers == QtCore.Qt.ShiftModifier:
  7216. # do not auto open the Project Tab
  7217. self.click_noproject = True
  7218. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7219. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7220. return
  7221. if self.doubleclick is True:
  7222. self.doubleclick = False
  7223. if self.collection.get_selected():
  7224. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7225. if self.ui.splitter.sizes()[0] == 0:
  7226. self.ui.splitter.setSizes([1, 1])
  7227. try:
  7228. # delete the selection shape(S) as it may be in the way
  7229. self.delete_selection_shape()
  7230. self.delete_hover_shape()
  7231. except Exception as e:
  7232. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7233. return
  7234. else:
  7235. if self.selection_type is not None:
  7236. try:
  7237. self.selection_area_handler(self.pos, pos, self.selection_type)
  7238. self.selection_type = None
  7239. except Exception as e:
  7240. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7241. return
  7242. else:
  7243. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7244. if key_modifier == QtCore.Qt.ShiftModifier:
  7245. mod_key = 'Shift'
  7246. elif key_modifier == QtCore.Qt.ControlModifier:
  7247. mod_key = 'Control'
  7248. else:
  7249. mod_key = None
  7250. try:
  7251. if mod_key == self.defaults["global_mselect_key"]:
  7252. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7253. # deselect, and if it's not selected then it will be selected
  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(key='CTRL')
  7258. self.delete_hover_shape()
  7259. else:
  7260. # If there is no active command (self.command_active is None) then we check if we clicked
  7261. # on a object by checking the bounding limits against mouse click position
  7262. if self.command_active is None:
  7263. self.select_objects()
  7264. self.delete_hover_shape()
  7265. except Exception as e:
  7266. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7267. return
  7268. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7269. """
  7270. :param start_pos: mouse position when the selection LMB click was done
  7271. :param end_pos: mouse position when the left mouse button is released
  7272. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7273. :return:
  7274. """
  7275. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7276. # delete previous selection shape
  7277. self.delete_selection_shape()
  7278. # make all objects inactive
  7279. self.collection.set_all_inactive()
  7280. for obj in self.collection.get_list():
  7281. try:
  7282. # select the object(s) only if it is enabled (plotted)
  7283. if obj.options['plot']:
  7284. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7285. (obj.options['xmax'], obj.options['ymin']),
  7286. (obj.options['xmax'], obj.options['ymax']),
  7287. (obj.options['xmin'], obj.options['ymax'])])
  7288. if sel_type is True:
  7289. if poly_obj.within(poly_selection):
  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. else:
  7295. if poly_selection.intersects(poly_obj):
  7296. # create the selection box around the selected object
  7297. if self.defaults['global_selection_shape'] is True:
  7298. self.draw_selection_shape(obj)
  7299. self.collection.set_active(obj.options['name'])
  7300. except Exception as e:
  7301. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7302. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7303. # In this case poly_obj creation (see above) will fail
  7304. log.debug("App.selection_area_handler() --> %s" % str(e))
  7305. def select_objects(self, key=None):
  7306. """
  7307. Will select objects clicked on canvas
  7308. :param key: for future use in cumulative selection
  7309. :return:
  7310. """
  7311. # list where we store the overlapped objects under our mouse left click position
  7312. objects_under_the_click_list = []
  7313. # Populate the list with the overlapped objects on the click position
  7314. curr_x, curr_y = self.pos
  7315. for obj in self.all_objects_list:
  7316. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7317. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7318. continue
  7319. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7320. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7321. if obj.options['name'] not in objects_under_the_click_list:
  7322. if obj.options['plot']:
  7323. # add objects to the objects_under_the_click list only if the object is plotted
  7324. # (active and not disabled)
  7325. objects_under_the_click_list.append(obj.options['name'])
  7326. try:
  7327. if objects_under_the_click_list:
  7328. curr_sel_obj = self.collection.get_active()
  7329. # case when there is only an object under the click and we toggle it
  7330. if len(objects_under_the_click_list) == 1:
  7331. if curr_sel_obj is None:
  7332. self.collection.set_active(objects_under_the_click_list[0])
  7333. curr_sel_obj = self.collection.get_active()
  7334. # create the selection box around the selected object
  7335. if self.defaults['global_selection_shape'] is True:
  7336. self.draw_selection_shape(curr_sel_obj)
  7337. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7338. self.on_objects_selection(False)
  7339. self.delete_selection_shape()
  7340. self.collection.set_active(objects_under_the_click_list[0])
  7341. curr_sel_obj = self.collection.get_active()
  7342. # create the selection box around the selected object
  7343. if self.defaults['global_selection_shape'] is True:
  7344. self.draw_selection_shape(curr_sel_obj)
  7345. self.selected_message(curr_sel_obj=curr_sel_obj)
  7346. else:
  7347. self.on_objects_selection(False)
  7348. self.delete_selection_shape()
  7349. if self.call_source != 'app':
  7350. self.call_source = 'app'
  7351. self.selected_message(curr_sel_obj=curr_sel_obj)
  7352. else:
  7353. # If there is no selected object
  7354. # make active the first element of the overlapped objects list
  7355. if self.collection.get_active() is None:
  7356. self.collection.set_active(objects_under_the_click_list[0])
  7357. name_sel_obj = self.collection.get_active().options['name']
  7358. # In case that there is a selected object but it is not in the overlapped object list
  7359. # make that object inactive and activate the first element in the overlapped object list
  7360. if name_sel_obj not in objects_under_the_click_list:
  7361. self.collection.set_inactive(name_sel_obj)
  7362. name_sel_obj = objects_under_the_click_list[0]
  7363. self.collection.set_active(name_sel_obj)
  7364. else:
  7365. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7366. self.collection.set_all_inactive()
  7367. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7368. len(objects_under_the_click_list)])
  7369. curr_sel_obj = self.collection.get_active()
  7370. # delete the possible selection box around a possible selected object
  7371. self.delete_selection_shape()
  7372. # create the selection box around the selected object
  7373. if self.defaults['global_selection_shape'] is True:
  7374. self.draw_selection_shape(curr_sel_obj)
  7375. self.selected_message(curr_sel_obj=curr_sel_obj)
  7376. else:
  7377. # deselect everything
  7378. self.on_objects_selection(False)
  7379. # delete the possible selection box around a possible selected object
  7380. self.delete_selection_shape()
  7381. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7382. # only when working on App
  7383. if self.call_source == 'app':
  7384. if self.click_noproject is False:
  7385. # if the Tool Tab is in focus don't change focus to Project Tab
  7386. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7387. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7388. else:
  7389. # restore auto open the Project Tab
  7390. self.click_noproject = False
  7391. # delete any text in the status bar, implicitly the last object name that was selected
  7392. # self.inform.emit("")
  7393. else:
  7394. self.call_source = 'app'
  7395. except Exception as e:
  7396. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7397. def selected_message(self, curr_sel_obj):
  7398. if curr_sel_obj:
  7399. if curr_sel_obj.kind == 'gerber':
  7400. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7401. color='green', name=str(curr_sel_obj.options['name'])))
  7402. elif curr_sel_obj.kind == 'excellon':
  7403. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7404. color='brown', name=str(curr_sel_obj.options['name'])))
  7405. elif curr_sel_obj.kind == 'cncjob':
  7406. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7407. color='blue', name=str(curr_sel_obj.options['name'])))
  7408. elif curr_sel_obj.kind == 'geometry':
  7409. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7410. color='red', name=str(curr_sel_obj.options['name'])))
  7411. def delete_hover_shape(self):
  7412. self.hover_shapes.clear()
  7413. self.hover_shapes.redraw()
  7414. def draw_hover_shape(self, sel_obj, color=None):
  7415. """
  7416. :param sel_obj: the object for which the hover shape must be drawn
  7417. :return:
  7418. """
  7419. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7420. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7421. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7422. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7423. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7424. if self.defaults['units'].upper() == 'MM':
  7425. hover_rect = hover_rect.buffer(-0.1)
  7426. hover_rect = hover_rect.buffer(0.2)
  7427. else:
  7428. hover_rect = hover_rect.buffer(-0.00393)
  7429. hover_rect = hover_rect.buffer(0.00787)
  7430. # if color:
  7431. # face = Color(color)
  7432. # face.alpha = 0.2
  7433. # outline = Color(color, alpha=0.8)
  7434. # else:
  7435. # face = Color(self.defaults['global_sel_fill'])
  7436. # face.alpha = 0.2
  7437. # outline = self.defaults['global_sel_line']
  7438. if color:
  7439. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7440. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7441. else:
  7442. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7443. outline = self.defaults['global_sel_line']
  7444. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7445. if self.is_legacy is True:
  7446. self.hover_shapes.redraw()
  7447. def delete_selection_shape(self):
  7448. self.move_tool.sel_shapes.clear()
  7449. self.move_tool.sel_shapes.redraw()
  7450. def draw_selection_shape(self, sel_obj, color=None):
  7451. """
  7452. :param sel_obj: the object for which the selection shape must be drawn
  7453. :return:
  7454. """
  7455. if sel_obj is None:
  7456. return
  7457. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7458. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7459. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7460. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7461. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7462. if self.defaults['units'].upper() == 'MM':
  7463. sel_rect = sel_rect.buffer(-0.1)
  7464. sel_rect = sel_rect.buffer(0.2)
  7465. else:
  7466. sel_rect = sel_rect.buffer(-0.00393)
  7467. sel_rect = sel_rect.buffer(0.00787)
  7468. if color:
  7469. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7470. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7471. else:
  7472. if self.is_legacy is False:
  7473. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7474. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7475. else:
  7476. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7477. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7478. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7479. color=outline,
  7480. face_color=face,
  7481. update=True,
  7482. layer=0,
  7483. tolerance=None))
  7484. if self.is_legacy is True:
  7485. self.move_tool.sel_shapes.redraw()
  7486. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7487. """
  7488. :param old_coords: old coordinates
  7489. :param coords: new coordinates
  7490. :return:
  7491. """
  7492. if 'color' in kwargs:
  7493. color = kwargs['color']
  7494. else:
  7495. color = self.defaults['global_sel_line']
  7496. if 'face_color' in kwargs:
  7497. face_color = kwargs['face_color']
  7498. else:
  7499. face_color = self.defaults['global_sel_fill']
  7500. if 'face_alpha' in kwargs:
  7501. face_alpha = kwargs['face_alpha']
  7502. else:
  7503. face_alpha = 0.3
  7504. x0, y0 = old_coords
  7505. x1, y1 = coords
  7506. pt1 = (x0, y0)
  7507. pt2 = (x1, y0)
  7508. pt3 = (x1, y1)
  7509. pt4 = (x0, y1)
  7510. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7511. # color_t = Color(face_color)
  7512. # color_t.alpha = face_alpha
  7513. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7514. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7515. layer=0, tolerance=None)
  7516. if self.is_legacy is True:
  7517. self.move_tool.sel_shapes.redraw()
  7518. def on_file_new_click(self):
  7519. if self.collection.get_list() and self.should_we_save:
  7520. msgbox = QtWidgets.QMessageBox()
  7521. # msgbox.setText("<B>Save changes ...</B>")
  7522. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7523. "Creating a New project will delete them.\n"
  7524. "Do you want to Save the project?"))
  7525. msgbox.setWindowTitle(_("Save changes"))
  7526. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7527. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7528. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7529. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7530. msgbox.setDefaultButton(bt_yes)
  7531. msgbox.exec_()
  7532. response = msgbox.clickedButton()
  7533. if response == bt_yes:
  7534. self.on_file_saveprojectas()
  7535. elif response == bt_cancel:
  7536. return
  7537. elif response == bt_no:
  7538. self.on_file_new()
  7539. else:
  7540. self.on_file_new()
  7541. self.inform.emit('[success] %s...' %
  7542. _("New Project created"))
  7543. def on_file_new(self, cli=None):
  7544. """
  7545. Callback for menu item File -> New. Returns the application to its
  7546. startup state. This method is thread-safe.
  7547. :return: None
  7548. """
  7549. self.report_usage("on_file_new")
  7550. # Remove everything from memory
  7551. App.log.debug("on_file_new()")
  7552. if self.call_source != 'app':
  7553. self.editor2object(cleanup=True)
  7554. # ## EDITOR section
  7555. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7556. self.exc_editor = FlatCAMExcEditor(self)
  7557. self.grb_editor = FlatCAMGrbEditor(self)
  7558. # Clear pool
  7559. self.clear_pool()
  7560. for obj in self.collection.get_list():
  7561. # delete shapes left drawn from mark shape_collections, if any
  7562. if isinstance(obj, FlatCAMGerber):
  7563. try:
  7564. obj.mark_shapes.enabled = False
  7565. obj.mark_shapes.clear(update=True)
  7566. except AttributeError:
  7567. pass
  7568. # also delete annotation shapes, if any
  7569. elif isinstance(obj, FlatCAMCNCjob):
  7570. try:
  7571. obj.annotation.enabled = False
  7572. obj.annotation.clear(update=True)
  7573. except AttributeError:
  7574. pass
  7575. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7576. self.init_tcl()
  7577. self.delete_selection_shape()
  7578. self.collection.delete_all()
  7579. self.setup_component_editor()
  7580. # Clear project filename
  7581. self.project_filename = None
  7582. # Load the application defaults
  7583. self.load_defaults(filename='current_defaults')
  7584. # Re-fresh project options
  7585. self.on_options_app2project()
  7586. # Init Tools
  7587. self.init_tools()
  7588. if cli is None:
  7589. # Close any Tabs opened in the Plot Tab Area section
  7590. for index in range(self.ui.plot_tab_area.count()):
  7591. self.ui.plot_tab_area.closeTab(index)
  7592. # for whatever reason previous command does not close the last tab so I do it manually
  7593. self.ui.plot_tab_area.closeTab(0)
  7594. # # And then add again the Plot Area
  7595. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7596. self.ui.plot_tab_area.protectTab(0)
  7597. # take the focus of the Notebook on Project Tab.
  7598. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7599. self.set_ui_title(name=_("New Project - Not saved"))
  7600. def obj_properties(self):
  7601. """
  7602. Will launch the object Properties Tool
  7603. :return:
  7604. """
  7605. self.report_usage("obj_properties()")
  7606. self.properties_tool.run(toggle=False)
  7607. def on_project_context_save(self):
  7608. """
  7609. Wrapper, will save the object function of it's type
  7610. :return:
  7611. """
  7612. obj = self.collection.get_active()
  7613. if type(obj) == FlatCAMGeometry:
  7614. self.on_file_exportdxf()
  7615. elif type(obj) == FlatCAMExcellon:
  7616. self.on_file_saveexcellon()
  7617. elif type(obj) == FlatCAMCNCjob:
  7618. obj.on_exportgcode_button_click()
  7619. elif type(obj) == FlatCAMGerber:
  7620. self.on_file_savegerber()
  7621. elif type(obj) == FlatCAMScript:
  7622. self.on_file_savescript()
  7623. elif type(obj) == FlatCAMDocument:
  7624. self.on_file_savedocument()
  7625. def obj_move(self):
  7626. self.report_usage("obj_move()")
  7627. self.move_tool.run(toggle=False)
  7628. def on_fileopengerber(self, signal: bool = None, name=None):
  7629. """
  7630. File menu callback for opening a Gerber.
  7631. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7632. :return: None
  7633. """
  7634. self.report_usage("on_fileopengerber")
  7635. App.log.debug("on_fileopengerber()")
  7636. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7637. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7638. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7639. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7640. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7641. "*.mil);;" \
  7642. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7643. "Allegro Files (*.art);;" \
  7644. "Mentor Files (*.pho *.gdo);;" \
  7645. "All Files (*.*)"
  7646. if name is None:
  7647. try:
  7648. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7649. directory=self.get_last_folder(),
  7650. filter=_filter_)
  7651. except TypeError:
  7652. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7653. filenames = [str(filename) for filename in filenames]
  7654. else:
  7655. filenames = [name]
  7656. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7657. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7658. _("Opening Gerber file.")),
  7659. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7660. color=QtGui.QColor("gray"))
  7661. if len(filenames) == 0:
  7662. self.inform.emit('[WARNING_NOTCL] %s' %
  7663. _("Open Gerber cancelled."))
  7664. else:
  7665. for filename in filenames:
  7666. if filename != '':
  7667. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7668. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7669. """
  7670. File menu callback for opening an Excellon file.
  7671. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7672. :return: None
  7673. """
  7674. self.report_usage("on_fileopenexcellon")
  7675. App.log.debug("on_fileopenexcellon()")
  7676. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7677. "All Files (*.*)"
  7678. if name is None:
  7679. try:
  7680. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7681. directory=self.get_last_folder(),
  7682. filter=_filter_)
  7683. except TypeError:
  7684. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7685. filenames = [str(filename) for filename in filenames]
  7686. else:
  7687. filenames = [str(name)]
  7688. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7689. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7690. _("Opening Excellon file.")),
  7691. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7692. color=QtGui.QColor("gray"))
  7693. if len(filenames) == 0:
  7694. self.inform.emit('[WARNING_NOTCL]%s' %
  7695. _(" Open Excellon cancelled."))
  7696. else:
  7697. for filename in filenames:
  7698. if filename != '':
  7699. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7700. def on_fileopengcode(self, signal: bool = None, name=None):
  7701. """
  7702. File menu call back for opening gcode.
  7703. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7704. :return: None
  7705. """
  7706. self.report_usage("on_fileopengcode")
  7707. App.log.debug("on_fileopengcode()")
  7708. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7709. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7710. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7711. "All Files (*.*)"
  7712. if name is None:
  7713. try:
  7714. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7715. directory=self.get_last_folder(),
  7716. filter=_filter_)
  7717. except TypeError:
  7718. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7719. filenames = [str(filename) for filename in filenames]
  7720. else:
  7721. filenames = [name]
  7722. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7723. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7724. _("Opening G-Code file.")),
  7725. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7726. color=QtGui.QColor("gray"))
  7727. if len(filenames) == 0:
  7728. self.inform.emit('[WARNING_NOTCL] %s' %
  7729. _("Open G-Code cancelled."))
  7730. else:
  7731. for filename in filenames:
  7732. if filename != '':
  7733. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7734. def on_file_openproject(self, signal: bool = None):
  7735. """
  7736. File menu callback for opening a project.
  7737. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7738. :return: None
  7739. """
  7740. self.report_usage("on_file_openproject")
  7741. App.log.debug("on_file_openproject()")
  7742. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7743. try:
  7744. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7745. directory=self.get_last_folder(), filter=_filter_)
  7746. except TypeError:
  7747. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7748. # The Qt methods above will return a QString which can cause problems later.
  7749. # So far json.dump() will fail to serialize it.
  7750. # TODO: Improve the serialization methods and remove this fix.
  7751. filename = str(filename)
  7752. if filename == "":
  7753. self.inform.emit('[WARNING_NOTCL] %s' %
  7754. _("Open Project cancelled."))
  7755. else:
  7756. # self.worker_task.emit({'fcn': self.open_project,
  7757. # 'params': [filename]})
  7758. # The above was failing because open_project() is not
  7759. # thread safe. The new_project()
  7760. self.open_project(filename)
  7761. def on_file_openconfig(self, signal: bool = None):
  7762. """
  7763. File menu callback for opening a config file.
  7764. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7765. :return: None
  7766. """
  7767. self.report_usage("on_file_openconfig")
  7768. App.log.debug("on_file_openconfig()")
  7769. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7770. try:
  7771. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7772. directory=self.data_path, filter=_filter_)
  7773. except TypeError:
  7774. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7775. filter=_filter_)
  7776. if filename == "":
  7777. self.inform.emit('[WARNING_NOTCL] %s' %
  7778. _("Open Config cancelled."))
  7779. else:
  7780. self.open_config_file(filename)
  7781. def on_file_exportsvg(self):
  7782. """
  7783. Callback for menu item File->Export SVG.
  7784. :return: None
  7785. """
  7786. self.report_usage("on_file_exportsvg")
  7787. App.log.debug("on_file_exportsvg()")
  7788. obj = self.collection.get_active()
  7789. if obj is None:
  7790. self.inform.emit('[WARNING_NOTCL] %s' %
  7791. _("No object selected."))
  7792. msg = _("Please Select a Geometry object to export")
  7793. msgbox = QtWidgets.QMessageBox()
  7794. msgbox.setInformativeText(msg)
  7795. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7796. msgbox.setDefaultButton(bt_ok)
  7797. msgbox.exec_()
  7798. return
  7799. # Check for more compatible types and add as required
  7800. if (not isinstance(obj, FlatCAMGeometry)
  7801. and not isinstance(obj, FlatCAMGerber)
  7802. and not isinstance(obj, FlatCAMCNCjob)
  7803. and not isinstance(obj, FlatCAMExcellon)):
  7804. msg = '[ERROR_NOTCL] %s' % \
  7805. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7806. msgbox = QtWidgets.QMessageBox()
  7807. msgbox.setInformativeText(msg)
  7808. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7809. msgbox.setDefaultButton(bt_ok)
  7810. msgbox.exec_()
  7811. return
  7812. name = obj.options["name"]
  7813. _filter = "SVG File (*.svg);;All Files (*.*)"
  7814. try:
  7815. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7816. caption=_("Export SVG"),
  7817. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7818. filter=_filter)
  7819. except TypeError:
  7820. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7821. filename = str(filename)
  7822. if filename == "":
  7823. self.inform.emit('[WARNING_NOTCL]%s' %
  7824. _(" Export SVG cancelled."))
  7825. return
  7826. else:
  7827. self.export_svg(name, filename)
  7828. if self.defaults["global_open_style"] is False:
  7829. self.file_opened.emit("SVG", filename)
  7830. self.file_saved.emit("SVG", filename)
  7831. def on_file_exportpng(self):
  7832. self.report_usage("on_file_exportpng")
  7833. App.log.debug("on_file_exportpng()")
  7834. self.date = str(datetime.today()).rpartition('.')[0]
  7835. self.date = ''.join(c for c in self.date if c not in ':-')
  7836. self.date = self.date.replace(' ', '_')
  7837. if self.is_legacy is False:
  7838. image = _screenshot()
  7839. data = np.asarray(image)
  7840. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7841. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7842. _('Data must be a 3D array with last dimension 3 or 4'))
  7843. return
  7844. filter_ = "PNG File (*.png);;All Files (*.*)"
  7845. try:
  7846. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7847. caption=_("Export PNG Image"),
  7848. directory=self.get_last_save_folder() + '/png_' + self.date,
  7849. filter=filter_)
  7850. except TypeError:
  7851. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7852. filename = str(filename)
  7853. if filename == "":
  7854. self.inform.emit(_("Export PNG cancelled."))
  7855. return
  7856. else:
  7857. if self.is_legacy is False:
  7858. write_png(filename, data)
  7859. else:
  7860. self.plotcanvas.figure.savefig(filename)
  7861. if self.defaults["global_open_style"] is False:
  7862. self.file_opened.emit("png", filename)
  7863. self.file_saved.emit("png", filename)
  7864. def on_file_savegerber(self):
  7865. """
  7866. Callback for menu item in Project context menu.
  7867. :return: None
  7868. """
  7869. self.report_usage("on_file_savegerber")
  7870. App.log.debug("on_file_savegerber()")
  7871. obj = self.collection.get_active()
  7872. if obj is None:
  7873. self.inform.emit('[WARNING_NOTCL] %s' %
  7874. _("No object selected. Please select an Gerber object to export."))
  7875. return
  7876. # Check for more compatible types and add as required
  7877. if not isinstance(obj, FlatCAMGerber):
  7878. self.inform.emit('[ERROR_NOTCL] %s' %
  7879. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7880. return
  7881. name = self.collection.get_active().options["name"]
  7882. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7883. try:
  7884. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7885. caption="Save Gerber source file",
  7886. directory=self.get_last_save_folder() + '/' + name,
  7887. filter=_filter)
  7888. except TypeError:
  7889. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7890. filename = str(filename)
  7891. if filename == "":
  7892. self.inform.emit('[WARNING_NOTCL] %s' %
  7893. _("Save Gerber source file cancelled."))
  7894. return
  7895. else:
  7896. self.save_source_file(name, filename)
  7897. if self.defaults["global_open_style"] is False:
  7898. self.file_opened.emit("Gerber", filename)
  7899. self.file_saved.emit("Gerber", filename)
  7900. def on_file_savescript(self):
  7901. """
  7902. Callback for menu item in Project context menu.
  7903. :return: None
  7904. """
  7905. self.report_usage("on_file_savescript")
  7906. App.log.debug("on_file_savescript()")
  7907. obj = self.collection.get_active()
  7908. if obj is None:
  7909. self.inform.emit('[WARNING_NOTCL] %s' %
  7910. _("No object selected. Please select an Script object to export."))
  7911. return
  7912. # Check for more compatible types and add as required
  7913. if not isinstance(obj, FlatCAMScript):
  7914. self.inform.emit('[ERROR_NOTCL] %s' %
  7915. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7916. return
  7917. name = self.collection.get_active().options["name"]
  7918. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7919. try:
  7920. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7921. caption="Save Script source file",
  7922. directory=self.get_last_save_folder() + '/' + name,
  7923. filter=_filter)
  7924. except TypeError:
  7925. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7926. filename = str(filename)
  7927. if filename == "":
  7928. self.inform.emit('[WARNING_NOTCL] %s' %
  7929. _("Save Script source file cancelled."))
  7930. return
  7931. else:
  7932. self.save_source_file(name, filename)
  7933. if self.defaults["global_open_style"] is False:
  7934. self.file_opened.emit("Script", filename)
  7935. self.file_saved.emit("Script", filename)
  7936. def on_file_savedocument(self):
  7937. """
  7938. Callback for menu item in Project context menu.
  7939. :return: None
  7940. """
  7941. self.report_usage("on_file_savedocument")
  7942. App.log.debug("on_file_savedocument()")
  7943. obj = self.collection.get_active()
  7944. if obj is None:
  7945. self.inform.emit('[WARNING_NOTCL] %s' %
  7946. _("No object selected. Please select an Document object to export."))
  7947. return
  7948. # Check for more compatible types and add as required
  7949. if not isinstance(obj, FlatCAMScript):
  7950. self.inform.emit('[ERROR_NOTCL] %s' %
  7951. _("Failed. Only Document objects can be saved as Document files..."))
  7952. return
  7953. name = self.collection.get_active().options["name"]
  7954. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7955. try:
  7956. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7957. caption="Save Document source file",
  7958. directory=self.get_last_save_folder() + '/' + name,
  7959. filter=_filter)
  7960. except TypeError:
  7961. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7962. filename = str(filename)
  7963. if filename == "":
  7964. self.inform.emit('[WARNING_NOTCL] %s' %
  7965. _("Save Document source file cancelled."))
  7966. return
  7967. else:
  7968. self.save_source_file(name, filename)
  7969. if self.defaults["global_open_style"] is False:
  7970. self.file_opened.emit("Document", filename)
  7971. self.file_saved.emit("Document", filename)
  7972. def on_file_saveexcellon(self):
  7973. """
  7974. Callback for menu item in project context menu.
  7975. :return: None
  7976. """
  7977. self.report_usage("on_file_saveexcellon")
  7978. App.log.debug("on_file_saveexcellon()")
  7979. obj = self.collection.get_active()
  7980. if obj is None:
  7981. self.inform.emit('[WARNING_NOTCL] %s' %
  7982. _("No object selected. Please select an Excellon object to export."))
  7983. return
  7984. # Check for more compatible types and add as required
  7985. if not isinstance(obj, FlatCAMExcellon):
  7986. self.inform.emit('[ERROR_NOTCL] %s' %
  7987. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7988. return
  7989. name = self.collection.get_active().options["name"]
  7990. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7991. try:
  7992. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7993. caption=_("Save Excellon source file"),
  7994. directory=self.get_last_save_folder() + '/' + name,
  7995. filter=_filter)
  7996. except TypeError:
  7997. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7998. filename = str(filename)
  7999. if filename == "":
  8000. self.inform.emit('[WARNING_NOTCL] %s' %
  8001. _("Saving Excellon source file cancelled."))
  8002. return
  8003. else:
  8004. self.save_source_file(name, filename)
  8005. if self.defaults["global_open_style"] is False:
  8006. self.file_opened.emit("Excellon", filename)
  8007. self.file_saved.emit("Excellon", filename)
  8008. def on_file_exportexcellon(self):
  8009. """
  8010. Callback for menu item File->Export->Excellon.
  8011. :return: None
  8012. """
  8013. self.report_usage("on_file_exportexcellon")
  8014. App.log.debug("on_file_exportexcellon()")
  8015. obj = self.collection.get_active()
  8016. if obj is None:
  8017. self.inform.emit('[WARNING_NOTCL] %s' %
  8018. _("No object selected. Please Select an Excellon object to export."))
  8019. return
  8020. # Check for more compatible types and add as required
  8021. if not isinstance(obj, FlatCAMExcellon):
  8022. self.inform.emit('[ERROR_NOTCL] %s' %
  8023. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8024. return
  8025. name = self.collection.get_active().options["name"]
  8026. _filter = self.defaults["excellon_save_filters"]
  8027. try:
  8028. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8029. caption=_("Export Excellon"),
  8030. directory=self.get_last_save_folder() + '/' + name,
  8031. filter=_filter)
  8032. except TypeError:
  8033. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8034. filename = str(filename)
  8035. if filename == "":
  8036. self.inform.emit('[WARNING_NOTCL] %s' %
  8037. _("Export Excellon cancelled."))
  8038. return
  8039. else:
  8040. used_extension = filename.rpartition('.')[2]
  8041. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8042. self.export_excellon(name, filename)
  8043. if self.defaults["global_open_style"] is False:
  8044. self.file_opened.emit("Excellon", filename)
  8045. self.file_saved.emit("Excellon", filename)
  8046. def on_file_exportgerber(self):
  8047. """
  8048. Callback for menu item File->Export->Gerber.
  8049. :return: None
  8050. """
  8051. self.report_usage("on_file_exportgerber")
  8052. App.log.debug("on_file_exportgerber()")
  8053. obj = self.collection.get_active()
  8054. if obj is None:
  8055. self.inform.emit('[WARNING_NOTCL] %s' %
  8056. _("No object selected. Please Select an Gerber object to export."))
  8057. return
  8058. # Check for more compatible types and add as required
  8059. if not isinstance(obj, FlatCAMGerber):
  8060. self.inform.emit('[ERROR_NOTCL] %s' %
  8061. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8062. return
  8063. name = self.collection.get_active().options["name"]
  8064. _filter_ = self.defaults['gerber_save_filters']
  8065. try:
  8066. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8067. caption=_("Export Gerber"),
  8068. directory=self.get_last_save_folder() + '/' + name,
  8069. filter=_filter_)
  8070. except TypeError:
  8071. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8072. filename = str(filename)
  8073. if filename == "":
  8074. self.inform.emit('[WARNING_NOTCL] %s' %
  8075. _("Export Gerber cancelled."))
  8076. return
  8077. else:
  8078. used_extension = filename.rpartition('.')[2]
  8079. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8080. self.export_gerber(name, filename)
  8081. if self.defaults["global_open_style"] is False:
  8082. self.file_opened.emit("Gerber", filename)
  8083. self.file_saved.emit("Gerber", filename)
  8084. def on_file_exportdxf(self):
  8085. """
  8086. Callback for menu item File->Export DXF.
  8087. :return: None
  8088. """
  8089. self.report_usage("on_file_exportdxf")
  8090. App.log.debug("on_file_exportdxf()")
  8091. obj = self.collection.get_active()
  8092. if obj is None:
  8093. self.inform.emit('[WARNING_NOTCL] %s' %
  8094. _("No object selected."))
  8095. msg = _("Please Select a Geometry object to export")
  8096. msgbox = QtWidgets.QMessageBox()
  8097. msgbox.setInformativeText(msg)
  8098. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8099. msgbox.setDefaultButton(bt_ok)
  8100. msgbox.exec_()
  8101. return
  8102. # Check for more compatible types and add as required
  8103. if not isinstance(obj, FlatCAMGeometry):
  8104. msg = '[ERROR_NOTCL] %s' % \
  8105. _("Only Geometry objects can be used.")
  8106. msgbox = QtWidgets.QMessageBox()
  8107. msgbox.setInformativeText(msg)
  8108. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8109. msgbox.setDefaultButton(bt_ok)
  8110. msgbox.exec_()
  8111. return
  8112. name = self.collection.get_active().options["name"]
  8113. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8114. try:
  8115. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8116. caption=_("Export DXF"),
  8117. directory=self.get_last_save_folder() + '/' + name,
  8118. filter=_filter_)
  8119. except TypeError:
  8120. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8121. filter=_filter_)
  8122. filename = str(filename)
  8123. if filename == "":
  8124. self.inform.emit('[WARNING_NOTCL] %s' %
  8125. _("Export DXF cancelled."))
  8126. return
  8127. else:
  8128. self.export_dxf(name, filename)
  8129. if self.defaults["global_open_style"] is False:
  8130. self.file_opened.emit("DXF", filename)
  8131. self.file_saved.emit("DXF", filename)
  8132. def on_file_importsvg(self, type_of_obj):
  8133. """
  8134. Callback for menu item File->Import SVG.
  8135. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8136. :type type_of_obj: str
  8137. :return: None
  8138. """
  8139. self.report_usage("on_file_importsvg")
  8140. App.log.debug("on_file_importsvg()")
  8141. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8142. try:
  8143. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8144. directory=self.get_last_folder(), filter=_filter_)
  8145. except TypeError:
  8146. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8147. filter=_filter_)
  8148. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8149. type_of_obj = "geometry"
  8150. filenames = [str(filename) for filename in filenames]
  8151. if len(filenames) == 0:
  8152. self.inform.emit('[WARNING_NOTCL] %s' %
  8153. _("Open SVG cancelled."))
  8154. else:
  8155. for filename in filenames:
  8156. if filename != '':
  8157. self.worker_task.emit({'fcn': self.import_svg,
  8158. 'params': [filename, type_of_obj]})
  8159. def on_file_importdxf(self, type_of_obj):
  8160. """
  8161. Callback for menu item File->Import DXF.
  8162. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8163. :type type_of_obj: str
  8164. :return: None
  8165. """
  8166. self.report_usage("on_file_importdxf")
  8167. App.log.debug("on_file_importdxf()")
  8168. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8169. try:
  8170. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8171. directory=self.get_last_folder(),
  8172. filter=_filter_)
  8173. except TypeError:
  8174. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8175. filter=_filter_)
  8176. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8177. type_of_obj = "geometry"
  8178. filenames = [str(filename) for filename in filenames]
  8179. if len(filenames) == 0:
  8180. self.inform.emit('[WARNING_NOTCL] %s' %
  8181. _("Open DXF cancelled."))
  8182. else:
  8183. for filename in filenames:
  8184. if filename != '':
  8185. self.worker_task.emit({'fcn': self.import_dxf,
  8186. 'params': [filename, type_of_obj]})
  8187. # ###############################################################################################################
  8188. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8189. # ###############################################################################################################
  8190. def init_code_editor(self, name):
  8191. self.text_editor_tab = TextEditor(app=self)
  8192. # add the tab if it was closed
  8193. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8194. self.text_editor_tab.setObjectName('text_editor_tab')
  8195. # delete the absolute and relative position and messages in the infobar
  8196. self.ui.position_label.setText("")
  8197. self.ui.rel_position_label.setText("")
  8198. # first clear previous text in text editor (if any)
  8199. self.text_editor_tab.code_editor.clear()
  8200. self.text_editor_tab.code_editor.setReadOnly(False)
  8201. self.toggle_codeeditor = True
  8202. self.text_editor_tab.code_editor.completer_enable = False
  8203. self.text_editor_tab.buttonRun.hide()
  8204. # make sure to keep a reference to the code editor
  8205. self.reference_code_editor = self.text_editor_tab.code_editor
  8206. # Switch plot_area to CNCJob tab
  8207. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8208. def on_view_source(self):
  8209. """
  8210. Called when the user wants to see the source file of the selected object
  8211. :return:
  8212. """
  8213. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8214. self.proc_container.view.set_busy(_("Loading..."))
  8215. try:
  8216. obj = self.collection.get_active()
  8217. except Exception as e:
  8218. log.debug("App.on_view_source() --> %s" % str(e))
  8219. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8220. return 'fail'
  8221. if obj is None:
  8222. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8223. return 'fail'
  8224. flt = "All Files (*.*)"
  8225. if obj.kind == 'gerber':
  8226. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8227. elif obj.kind == 'excellon':
  8228. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8229. elif obj.kind == 'cncjob':
  8230. "GCode Files (*.NC);;All Files (*.*)"
  8231. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8232. # add the tab if it was closed
  8233. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8234. self.source_editor_tab.setObjectName('source_editor_tab')
  8235. # delete the absolute and relative position and messages in the infobar
  8236. self.ui.position_label.setText("")
  8237. self.ui.rel_position_label.setText("")
  8238. # first clear previous text in text editor (if any)
  8239. self.source_editor_tab.code_editor.clear()
  8240. self.source_editor_tab.code_editor.setReadOnly(False)
  8241. self.source_editor_tab.code_editor.completer_enable = False
  8242. self.source_editor_tab.buttonRun.hide()
  8243. # Switch plot_area to CNCJob tab
  8244. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8245. try:
  8246. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8247. except TypeError:
  8248. pass
  8249. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8250. try:
  8251. self.source_editor_tab.buttonSave.clicked.disconnect()
  8252. except TypeError:
  8253. pass
  8254. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8255. # then append the text from GCode to the text editor
  8256. if obj.kind == 'cncjob':
  8257. try:
  8258. file = obj.export_gcode(
  8259. preamble=self.defaults["cncjob_prepend"],
  8260. postamble=self.defaults["cncjob_append"],
  8261. to_file=True)
  8262. if file == 'fail':
  8263. return 'fail'
  8264. except AttributeError:
  8265. self.inform.emit('[WARNING_NOTCL] %s' %
  8266. _("There is no selected object for which to see it's source file code."))
  8267. return 'fail'
  8268. else:
  8269. try:
  8270. file = StringIO(obj.source_file)
  8271. except (AttributeError, TypeError):
  8272. self.inform.emit('[WARNING_NOTCL] %s' %
  8273. _("There is no selected object for which to see it's source file code."))
  8274. return 'fail'
  8275. self.source_editor_tab.t_frame.hide()
  8276. try:
  8277. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8278. # for line in file:
  8279. # QtWidgets.QApplication.processEvents()
  8280. # proc_line = str(line).strip('\n')
  8281. # self.source_editor_tab.code_editor.append(proc_line)
  8282. except Exception as e:
  8283. log.debug('App.on_view_source() -->%s' % str(e))
  8284. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8285. return
  8286. self.source_editor_tab.handleTextChanged()
  8287. self.source_editor_tab.t_frame.show()
  8288. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8289. self.proc_container.view.set_idle()
  8290. # self.ui.show()
  8291. def on_toggle_code_editor(self):
  8292. self.report_usage("on_toggle_code_editor()")
  8293. if self.toggle_codeeditor is False:
  8294. self.init_code_editor(name=_("Code Editor"))
  8295. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8296. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8297. self.text_editor_tab.buttonSave.clicked.disconnect()
  8298. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8299. else:
  8300. for idx in range(self.ui.plot_tab_area.count()):
  8301. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8302. self.ui.plot_tab_area.closeTab(idx)
  8303. break
  8304. self.toggle_codeeditor = False
  8305. def on_code_editor_close(self):
  8306. print("closed")
  8307. self.toggle_codeeditor = False
  8308. def on_filenewscript(self, silent=False, name=None, text=None):
  8309. """
  8310. Will create a new script file and open it in the Code Editor
  8311. :param silent: if True will not display status messages
  8312. :param name: if specified will be the name of the new script
  8313. :param text: pass a source file to the newly created script to be loaded in it
  8314. :return: None
  8315. """
  8316. if silent is False:
  8317. self.inform.emit('[success] %s' %
  8318. _("New TCL script file created in Code Editor."))
  8319. # delete the absolute and relative position and messages in the infobar
  8320. self.ui.position_label.setText("")
  8321. self.ui.rel_position_label.setText("")
  8322. if name is not None:
  8323. self.new_script_object(name=name, text=text)
  8324. else:
  8325. self.new_script_object(text=text)
  8326. # script_text = script_obj.source_file
  8327. #
  8328. # self.proc_container.view.set_busy(_("Loading..."))
  8329. # script_obj.script_editor_tab.t_frame.hide()
  8330. #
  8331. # script_obj.script_editor_tab.t_frame.show()
  8332. # self.proc_container.view.set_idle()
  8333. def on_fileopenscript(self, name=None, silent=False):
  8334. """
  8335. Will open a Tcl script file into the Code Editor
  8336. :param silent: if True will not display status messages
  8337. :param name: name of a Tcl script file to open
  8338. :return:
  8339. """
  8340. self.report_usage("on_fileopenscript")
  8341. App.log.debug("on_fileopenscript()")
  8342. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8343. if name:
  8344. filenames = [name]
  8345. else:
  8346. try:
  8347. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8348. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8349. except TypeError:
  8350. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8351. if len(filenames) == 0:
  8352. if silent is False:
  8353. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8354. else:
  8355. for filename in filenames:
  8356. if filename != '':
  8357. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8358. def on_filerunscript(self, name=None, silent=False):
  8359. """
  8360. File menu callback for loading and running a TCL script.
  8361. :param silent: if True will not display status messages
  8362. :param name: name of a Tcl script file to be run by FlatCAM
  8363. :return: None
  8364. """
  8365. self.report_usage("on_filerunscript")
  8366. App.log.debug("on_file_runscript()")
  8367. if name:
  8368. filename = name
  8369. if self.cmd_line_headless != 1:
  8370. self.splash.showMessage('%s: %ssec\n%s' %
  8371. (_("Canvas initialization started.\n"
  8372. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8373. _("Executing FlatCAMScript file.")
  8374. ),
  8375. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8376. color=QtGui.QColor("gray"))
  8377. else:
  8378. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8379. try:
  8380. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8381. directory=self.get_last_folder(), filter=_filter_)
  8382. except TypeError:
  8383. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8384. # The Qt methods above will return a QString which can cause problems later.
  8385. # So far json.dump() will fail to serialize it.
  8386. # TODO: Improve the serialization methods and remove this fix.
  8387. filename = str(filename)
  8388. if filename == "":
  8389. if silent is False:
  8390. self.inform.emit('[WARNING_NOTCL] %s' %
  8391. _("Run TCL script cancelled."))
  8392. else:
  8393. if self.cmd_line_headless != 1:
  8394. if self.ui.shell_dock.isHidden():
  8395. self.ui.shell_dock.show()
  8396. try:
  8397. with open(filename, "r") as tcl_script:
  8398. cmd_line_shellfile_content = tcl_script.read()
  8399. if self.cmd_line_headless != 1:
  8400. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8401. else:
  8402. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8403. if silent is False:
  8404. self.inform.emit('[success] %s' %
  8405. _("TCL script file opened in Code Editor and executed."))
  8406. except Exception as e:
  8407. log.debug("App.on_filerunscript() -> %s" % str(e))
  8408. sys.exit(2)
  8409. def on_file_saveproject(self, silent=False):
  8410. """
  8411. Callback for menu item File->Save Project. Saves the project to
  8412. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8413. if set to None. The project is saved by calling ``self.save_project()``.
  8414. :param silent: if True will not display status messages
  8415. :return: None
  8416. """
  8417. self.report_usage("on_file_saveproject")
  8418. if self.project_filename is None:
  8419. self.on_file_saveprojectas()
  8420. else:
  8421. self.worker_task.emit({'fcn': self.save_project,
  8422. 'params': [self.project_filename, silent]})
  8423. if self.defaults["global_open_style"] is False:
  8424. self.file_opened.emit("project", self.project_filename)
  8425. self.file_saved.emit("project", self.project_filename)
  8426. self.set_ui_title(name=self.project_filename)
  8427. self.should_we_save = False
  8428. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8429. """
  8430. Callback for menu item File->Save Project As... Opens a file
  8431. chooser and saves the project to the given file via
  8432. ``self.save_project()``.
  8433. :param make_copy if to be create a copy of the project; boolean
  8434. :param use_thread: if to be run in a separate thread; boolean
  8435. :param quit_action: if to be followed by quiting the application; boolean
  8436. :return: None
  8437. """
  8438. self.report_usage("on_file_saveprojectas")
  8439. self.date = str(datetime.today()).rpartition('.')[0]
  8440. self.date = ''.join(c for c in self.date if c not in ':-')
  8441. self.date = self.date.replace(' ', '_')
  8442. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8443. try:
  8444. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8445. caption=_("Save Project As ..."),
  8446. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8447. filter=filter_)
  8448. except TypeError:
  8449. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8450. filename = str(filename)
  8451. if filename == '':
  8452. self.inform.emit('[WARNING_NOTCL] %s' %
  8453. _("Save Project cancelled."))
  8454. return
  8455. try:
  8456. f = open(filename, 'r')
  8457. f.close()
  8458. except IOError:
  8459. pass
  8460. if use_thread is True:
  8461. self.worker_task.emit({'fcn': self.save_project,
  8462. 'params': [filename, quit_action]})
  8463. else:
  8464. self.save_project(filename, quit_action)
  8465. # self.save_project(filename)
  8466. if self.defaults["global_open_style"] is False:
  8467. self.file_opened.emit("project", filename)
  8468. self.file_saved.emit("project", filename)
  8469. if not make_copy:
  8470. self.project_filename = filename
  8471. self.set_ui_title(name=self.project_filename)
  8472. self.should_we_save = False
  8473. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8474. """
  8475. Exports a Geometry Object to an SVG file.
  8476. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8477. :param filename: Path to the SVG file to save to.
  8478. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8479. :return:
  8480. """
  8481. self.report_usage("export_svg()")
  8482. if filename is None:
  8483. filename = self.defaults["global_last_save_folder"]
  8484. self.log.debug("export_svg()")
  8485. try:
  8486. obj = self.collection.get_by_name(str(obj_name))
  8487. except Exception:
  8488. # TODO: The return behavior has not been established... should raise exception?
  8489. return "Could not retrieve object: %s" % obj_name
  8490. with self.proc_container.new(_("Exporting SVG")) as proc:
  8491. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8492. # Determine bounding area for svg export
  8493. bounds = obj.bounds()
  8494. size = obj.size()
  8495. # Convert everything to strings for use in the xml doc
  8496. svgwidth = str(size[0])
  8497. svgheight = str(size[1])
  8498. minx = str(bounds[0])
  8499. miny = str(bounds[1] - size[1])
  8500. uom = obj.units.lower()
  8501. # Add a SVG Header and footer to the svg output from shapely
  8502. # The transform flips the Y Axis so that everything renders
  8503. # properly within svg apps such as inkscape
  8504. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8505. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8506. svg_header += 'width="' + svgwidth + uom + '" '
  8507. svg_header += 'height="' + svgheight + uom + '" '
  8508. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8509. svg_header += '<g transform="scale(1,-1)">'
  8510. svg_footer = '</g> </svg>'
  8511. svg_elem = svg_header + exported_svg + svg_footer
  8512. # Parse the xml through a xml parser just to add line feeds
  8513. # and to make it look more pretty for the output
  8514. svgcode = parse_xml_string(svg_elem)
  8515. svgcode = svgcode.toprettyxml()
  8516. try:
  8517. with open(filename, 'w') as fp:
  8518. fp.write(svgcode)
  8519. except PermissionError:
  8520. self.inform.emit('[WARNING] %s' %
  8521. _("Permission denied, saving not possible.\n"
  8522. "Most likely another app is holding the file open and not accessible."))
  8523. return 'fail'
  8524. if self.defaults["global_open_style"] is False:
  8525. self.file_opened.emit("SVG", filename)
  8526. self.file_saved.emit("SVG", filename)
  8527. self.inform.emit('[success] %s: %s' %
  8528. (_("SVG file exported to"), filename))
  8529. def save_source_file(self, obj_name, filename, use_thread=True):
  8530. """
  8531. Exports a FlatCAM Object to an Gerber/Excellon file.
  8532. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8533. :param filename: Path to the Gerber file to save to.
  8534. :param use_thread: if to be run in a separate thread
  8535. :return:
  8536. """
  8537. self.report_usage("save source file()")
  8538. if filename is None:
  8539. filename = self.defaults["global_last_save_folder"]
  8540. self.log.debug("save source file()")
  8541. obj = self.collection.get_by_name(obj_name)
  8542. file_string = StringIO(obj.source_file)
  8543. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8544. if file_string.getvalue() == '':
  8545. self.inform.emit('[ERROR_NOTCL] %s' %
  8546. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8547. return 'fail'
  8548. try:
  8549. with open(filename, 'w') as file:
  8550. file.writelines('G04*\n')
  8551. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8552. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8553. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8554. file.writelines('G04 Created on : %s*\n' % time_string)
  8555. for line in file_string:
  8556. file.writelines(line)
  8557. except PermissionError:
  8558. self.inform.emit('[WARNING] %s' %
  8559. _("Permission denied, saving not possible.\n"
  8560. "Most likely another app is holding the file open and not accessible."))
  8561. return 'fail'
  8562. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8563. """
  8564. Exports a Excellon Object to an Excellon file.
  8565. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8566. :param filename: Path to the Excellon file to save to.
  8567. :param local_use:
  8568. :param use_thread: if to be run in a separate thread
  8569. :return:
  8570. """
  8571. self.report_usage("export_excellon()")
  8572. if filename is None:
  8573. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8574. self.log.debug("export_excellon()")
  8575. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8576. self.defaults["excellon_exp_decimals"]
  8577. )
  8578. if local_use is None:
  8579. try:
  8580. obj = self.collection.get_by_name(str(obj_name))
  8581. except Exception:
  8582. # TODO: The return behavior has not been established... should raise exception?
  8583. return "Could not retrieve object: %s" % obj_name
  8584. else:
  8585. obj = local_use
  8586. if not isinstance(obj, FlatCAMExcellon):
  8587. self.inform.emit('[ERROR_NOTCL] %s' %
  8588. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8589. return
  8590. # updated units
  8591. eunits = self.defaults["excellon_exp_units"]
  8592. ewhole = self.defaults["excellon_exp_integer"]
  8593. efract = self.defaults["excellon_exp_decimals"]
  8594. ezeros = self.defaults["excellon_exp_zeros"]
  8595. eformat = self.defaults["excellon_exp_format"]
  8596. slot_type = self.defaults["excellon_exp_slot_type"]
  8597. fc_units = self.defaults['units'].upper()
  8598. if fc_units == 'MM':
  8599. factor = 1 if eunits == 'METRIC' else 0.03937
  8600. else:
  8601. factor = 25.4 if eunits == 'METRIC' else 1
  8602. def make_excellon():
  8603. try:
  8604. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8605. header = 'M48\n'
  8606. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8607. (str(self.version), str(self.version_date))
  8608. header += ';Filename: %s' % str(obj_name) + '\n'
  8609. header += ';Created on : %s' % time_str + '\n'
  8610. if eformat == 'dec':
  8611. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8612. header += eunits + '\n'
  8613. for tool in obj.tools:
  8614. if eunits == 'METRIC':
  8615. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8616. tool=str(tool),
  8617. dec=2)
  8618. else:
  8619. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8620. tool=str(tool),
  8621. dec=4)
  8622. else:
  8623. if ezeros == 'LZ':
  8624. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8625. form='ndec', e_zeros='LZ', factor=factor,
  8626. slot_type=slot_type)
  8627. header += '%s,%s\n' % (eunits, 'LZ')
  8628. header += format_exc
  8629. for tool in obj.tools:
  8630. if eunits == 'METRIC':
  8631. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8632. tool=str(tool),
  8633. dec=2)
  8634. else:
  8635. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8636. tool=str(tool),
  8637. dec=4)
  8638. else:
  8639. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8640. form='ndec', e_zeros='TZ', factor=factor,
  8641. slot_type=slot_type)
  8642. header += '%s,%s\n' % (eunits, 'TZ')
  8643. header += format_exc
  8644. for tool in obj.tools:
  8645. if eunits == 'METRIC':
  8646. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8647. tool=str(tool),
  8648. dec=2)
  8649. else:
  8650. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8651. tool=str(tool),
  8652. dec=4)
  8653. header += '%\n'
  8654. footer = 'M30\n'
  8655. exported_excellon = header
  8656. exported_excellon += excellon_code
  8657. exported_excellon += footer
  8658. if local_use is None:
  8659. try:
  8660. with open(filename, 'w') as fp:
  8661. fp.write(exported_excellon)
  8662. except PermissionError:
  8663. self.inform.emit('[WARNING] %s' %
  8664. _("Permission denied, saving not possible.\n"
  8665. "Most likely another app is holding the file open and not accessible."))
  8666. return 'fail'
  8667. if self.defaults["global_open_style"] is False:
  8668. self.file_opened.emit("Excellon", filename)
  8669. self.file_saved.emit("Excellon", filename)
  8670. self.inform.emit('[success] %s: %s' %
  8671. (_("Excellon file exported to"), filename))
  8672. else:
  8673. return exported_excellon
  8674. except Exception as e:
  8675. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8676. return 'fail'
  8677. if use_thread is True:
  8678. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8679. def job_thread_exc(app_obj):
  8680. ret = make_excellon()
  8681. if ret == 'fail':
  8682. self.inform.emit('[ERROR_NOTCL] %s' %
  8683. _('Could not export Excellon file.'))
  8684. return
  8685. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8686. else:
  8687. ret = make_excellon()
  8688. if ret == 'fail':
  8689. self.inform.emit('[ERROR_NOTCL] %s' %
  8690. _('Could not export Excellon file.'))
  8691. return 'fail'
  8692. if local_use is not None:
  8693. return ret
  8694. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8695. """
  8696. Exports a Gerber Object to an Gerber file.
  8697. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8698. :param filename: Path to the Gerber file to save to.
  8699. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8700. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8701. :param use_thread: if to be run in a separate thread
  8702. :return:
  8703. """
  8704. self.report_usage("export_gerber()")
  8705. if filename is None:
  8706. filename = self.defaults["global_last_save_folder"]
  8707. self.log.debug("export_gerber()")
  8708. if local_use is None:
  8709. try:
  8710. obj = self.collection.get_by_name(str(obj_name))
  8711. except Exception:
  8712. # TODO: The return behavior has not been established... should raise exception?
  8713. return "Could not retrieve object: %s" % obj_name
  8714. else:
  8715. obj = local_use
  8716. # updated units
  8717. gunits = self.defaults["gerber_exp_units"]
  8718. gwhole = self.defaults["gerber_exp_integer"]
  8719. gfract = self.defaults["gerber_exp_decimals"]
  8720. gzeros = self.defaults["gerber_exp_zeros"]
  8721. fc_units = self.defaults['units'].upper()
  8722. if fc_units == 'MM':
  8723. factor = 1 if gunits == 'MM' else 0.03937
  8724. else:
  8725. factor = 25.4 if gunits == 'MM' else 1
  8726. def make_gerber():
  8727. try:
  8728. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8729. header = 'G04*\n'
  8730. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8731. (str(self.version), str(self.version_date))
  8732. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8733. header += 'G04 Created on : %s*' % time_str + '\n'
  8734. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8735. header += "%MO{units}*%\n".format(units=gunits)
  8736. for apid in obj.apertures:
  8737. if obj.apertures[apid]['type'] == 'C':
  8738. header += "%ADD{apid}{type},{size}*%\n".format(
  8739. apid=str(apid),
  8740. type='C',
  8741. size=(factor * obj.apertures[apid]['size'])
  8742. )
  8743. elif obj.apertures[apid]['type'] == 'R':
  8744. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8745. apid=str(apid),
  8746. type='R',
  8747. width=(factor * obj.apertures[apid]['width']),
  8748. height=(factor * obj.apertures[apid]['height'])
  8749. )
  8750. elif obj.apertures[apid]['type'] == 'O':
  8751. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8752. apid=str(apid),
  8753. type='O',
  8754. width=(factor * obj.apertures[apid]['width']),
  8755. height=(factor * obj.apertures[apid]['height'])
  8756. )
  8757. header += '\n'
  8758. # obsolete units but some software may need it
  8759. if gunits == 'IN':
  8760. header += 'G70*\n'
  8761. else:
  8762. header += 'G71*\n'
  8763. # Absolute Mode
  8764. header += 'G90*\n'
  8765. header += 'G01*\n'
  8766. # positive polarity
  8767. header += '%LPD*%\n'
  8768. footer = 'M02*\n'
  8769. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8770. exported_gerber = header
  8771. exported_gerber += gerber_code
  8772. exported_gerber += footer
  8773. if local_use is None:
  8774. try:
  8775. with open(filename, 'w') as fp:
  8776. fp.write(exported_gerber)
  8777. except PermissionError:
  8778. self.inform.emit('[WARNING] %s' %
  8779. _("Permission denied, saving not possible.\n"
  8780. "Most likely another app is holding the file open and not accessible."))
  8781. return 'fail'
  8782. if self.defaults["global_open_style"] is False:
  8783. self.file_opened.emit("Gerber", filename)
  8784. self.file_saved.emit("Gerber", filename)
  8785. self.inform.emit('[success] %s: %s' %
  8786. (_("Gerber file exported to"), filename))
  8787. else:
  8788. return exported_gerber
  8789. except Exception as e:
  8790. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8791. return 'fail'
  8792. if use_thread is True:
  8793. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8794. def job_thread_grb(app_obj):
  8795. ret = make_gerber()
  8796. if ret == 'fail':
  8797. self.inform.emit('[ERROR_NOTCL] %s' %
  8798. _('Could not export Gerber file.'))
  8799. return
  8800. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8801. else:
  8802. ret = make_gerber()
  8803. if ret == 'fail':
  8804. self.inform.emit('[ERROR_NOTCL] %s' %
  8805. _('Could not export Gerber file.'))
  8806. return 'fail'
  8807. if local_use is not None:
  8808. return ret
  8809. def export_dxf(self, obj_name, filename, use_thread=True):
  8810. """
  8811. Exports a Geometry Object to an DXF file.
  8812. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8813. :param filename: Path to the DXF file to save to.
  8814. :param use_thread: if to be run in a separate thread
  8815. :return:
  8816. """
  8817. self.report_usage("export_dxf()")
  8818. if filename is None:
  8819. filename = self.defaults["global_last_save_folder"]
  8820. self.log.debug("export_dxf()")
  8821. try:
  8822. obj = self.collection.get_by_name(str(obj_name))
  8823. except Exception:
  8824. # TODO: The return behavior has not been established... should raise exception?
  8825. return "Could not retrieve object: %s" % obj_name
  8826. def make_dxf():
  8827. try:
  8828. dxf_code = obj.export_dxf()
  8829. dxf_code.saveas(filename)
  8830. if self.defaults["global_open_style"] is False:
  8831. self.file_opened.emit("DXF", filename)
  8832. self.file_saved.emit("DXF", filename)
  8833. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8834. except Exception:
  8835. return 'fail'
  8836. if use_thread is True:
  8837. with self.proc_container.new(_("Exporting DXF")) as proc:
  8838. def job_thread_exc(app_obj):
  8839. ret_dxf_val = make_dxf()
  8840. if ret_dxf_val == 'fail':
  8841. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8842. return
  8843. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8844. else:
  8845. ret = make_dxf()
  8846. if ret == 'fail':
  8847. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8848. return
  8849. def import_svg(self, filename, geo_type='geometry', outname=None):
  8850. """
  8851. Adds a new Geometry Object to the projects and populates
  8852. it with shapes extracted from the SVG file.
  8853. :param filename: Path to the SVG file.
  8854. :param geo_type: Type of FlatCAM object that will be created from SVG
  8855. :param outname:
  8856. :return:
  8857. """
  8858. self.report_usage("import_svg()")
  8859. log.debug("App.import_svg()")
  8860. obj_type = ""
  8861. if geo_type is None or geo_type == "geometry":
  8862. obj_type = "geometry"
  8863. elif geo_type == "gerber":
  8864. obj_type = "gerber"
  8865. else:
  8866. self.inform.emit('[ERROR_NOTCL] %s' %
  8867. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8868. return
  8869. units = self.defaults['units'].upper()
  8870. def obj_init(geo_obj, app_obj):
  8871. geo_obj.import_svg(filename, obj_type, units=units)
  8872. geo_obj.multigeo = False
  8873. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8874. with self.proc_container.new(_("Importing SVG")) as proc:
  8875. # Object name
  8876. name = outname or filename.split('/')[-1].split('\\')[-1]
  8877. self.new_object(obj_type, name, obj_init, autoselected=False)
  8878. # Register recent file
  8879. self.file_opened.emit("svg", filename)
  8880. # GUI feedback
  8881. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8882. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8883. """
  8884. Adds a new Geometry Object to the projects and populates
  8885. it with shapes extracted from the DXF file.
  8886. :param filename: Path to the DXF file.
  8887. :param geo_type: Type of FlatCAM object that will be created from DXF
  8888. :param outname:
  8889. :type putname: str
  8890. :return:
  8891. """
  8892. self.report_usage("import_dxf()")
  8893. obj_type = ""
  8894. if geo_type is None or geo_type == "geometry":
  8895. obj_type = "geometry"
  8896. elif geo_type == "gerber":
  8897. obj_type = geo_type
  8898. else:
  8899. self.inform.emit('[ERROR_NOTCL] %s' %
  8900. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8901. return
  8902. units = self.defaults['units'].upper()
  8903. def obj_init(geo_obj, app_obj):
  8904. geo_obj.import_dxf(filename, obj_type, units=units)
  8905. geo_obj.multigeo = False
  8906. with self.proc_container.new(_("Importing DXF")) as proc:
  8907. # Object name
  8908. name = outname or filename.split('/')[-1].split('\\')[-1]
  8909. self.new_object(obj_type, name, obj_init, autoselected=False)
  8910. self.progress.emit(20)
  8911. # Register recent file
  8912. self.file_opened.emit("dxf", filename)
  8913. # GUI feedback
  8914. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8915. self.progress.emit(100)
  8916. def open_gerber(self, filename, outname=None):
  8917. """
  8918. Opens a Gerber file, parses it and creates a new object for
  8919. it in the program. Thread-safe.
  8920. :param outname: Name of the resulting object. None causes the
  8921. name to be that of the file.
  8922. :param filename: Gerber file filename
  8923. :type filename: str
  8924. :return: None
  8925. """
  8926. # How the object should be initialized
  8927. def obj_init(gerber_obj, app_obj):
  8928. assert isinstance(gerber_obj, FlatCAMGerber), \
  8929. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8930. # Opening the file happens here
  8931. try:
  8932. gerber_obj.parse_file(filename)
  8933. except IOError:
  8934. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8935. return "fail"
  8936. except ParseError as err:
  8937. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8938. app_obj.log.error(str(err))
  8939. return "fail"
  8940. except Exception as e:
  8941. log.debug("App.open_gerber() --> %s" % str(e))
  8942. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8943. msg += traceback.format_exc()
  8944. app_obj.inform.emit(msg)
  8945. return "fail"
  8946. if gerber_obj.is_empty():
  8947. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8948. _("Object is not Gerber file or empty. Aborting object creation."))
  8949. return "fail"
  8950. App.log.debug("open_gerber()")
  8951. with self.proc_container.new(_("Opening Gerber")) as proc:
  8952. # Object name
  8953. name = outname or filename.split('/')[-1].split('\\')[-1]
  8954. # # ## Object creation # ##
  8955. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8956. if ret == 'fail':
  8957. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8958. return 'fail'
  8959. # Register recent file
  8960. self.file_opened.emit("gerber", filename)
  8961. # GUI feedback
  8962. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8963. def open_excellon(self, filename, outname=None, plot=True):
  8964. """
  8965. Opens an Excellon file, parses it and creates a new object for
  8966. it in the program. Thread-safe.
  8967. :param outname: Name of the resulting object. None causes the
  8968. name to be that of the file.
  8969. :param filename: Excellon file filename
  8970. :type filename: str
  8971. :return: None
  8972. """
  8973. App.log.debug("open_excellon()")
  8974. # How the object should be initialized
  8975. def obj_init(excellon_obj, app_obj):
  8976. # self.progress.emit(20)
  8977. try:
  8978. ret = excellon_obj.parse_file(filename=filename)
  8979. if ret == "fail":
  8980. log.debug("Excellon parsing failed.")
  8981. self.inform.emit('[ERROR_NOTCL] %s' %
  8982. _("This is not Excellon file."))
  8983. return "fail"
  8984. except IOError:
  8985. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8986. (_("Cannot open file"), filename))
  8987. log.debug("Could not open Excellon object.")
  8988. self.progress.emit(0) # TODO: self and app_bjj mixed
  8989. return "fail"
  8990. except Exception:
  8991. msg = '[ERROR_NOTCL] %s' % \
  8992. _("An internal error has occurred. See shell.\n")
  8993. msg += traceback.format_exc()
  8994. app_obj.inform.emit(msg)
  8995. return "fail"
  8996. ret = excellon_obj.create_geometry()
  8997. if ret == 'fail':
  8998. log.debug("Could not create geometry for Excellon object.")
  8999. return "fail"
  9000. for tool in excellon_obj.tools:
  9001. if excellon_obj.tools[tool]['solid_geometry']:
  9002. return
  9003. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9004. (_("No geometry found in file"), filename))
  9005. return "fail"
  9006. with self.proc_container.new(_("Opening Excellon.")):
  9007. # Object name
  9008. name = outname or filename.split('/')[-1].split('\\')[-1]
  9009. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9010. if ret_val == 'fail':
  9011. self.inform.emit('[ERROR_NOTCL] %s' %
  9012. _('Open Excellon file failed. Probable not an Excellon file.'))
  9013. return
  9014. # Register recent file
  9015. self.file_opened.emit("excellon", filename)
  9016. # GUI feedback
  9017. self.inform.emit('[success] %s: %s' %
  9018. (_("Opened"), filename))
  9019. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9020. """
  9021. Opens a G-gcode file, parses it and creates a new object for
  9022. it in the program. Thread-safe.
  9023. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9024. :param filename: G-code file filename
  9025. :type filename: str
  9026. :return: None
  9027. """
  9028. App.log.debug("open_gcode()")
  9029. # How the object should be initialized
  9030. def obj_init(job_obj, app_obj_):
  9031. """
  9032. :param job_obj: the resulting object
  9033. :type app_obj_: App
  9034. """
  9035. assert isinstance(app_obj_, App), \
  9036. "Initializer expected App, got %s" % type(app_obj_)
  9037. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9038. try:
  9039. f = open(filename)
  9040. gcode = f.read()
  9041. f.close()
  9042. except IOError:
  9043. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9044. (_("Failed to open"), filename))
  9045. return "fail"
  9046. job_obj.gcode = gcode
  9047. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9048. if gcode_ret == "fail":
  9049. self.inform.emit('[ERROR_NOTCL] %s' %
  9050. _("This is not GCODE"))
  9051. return "fail"
  9052. job_obj.create_geometry()
  9053. with self.proc_container.new(_("Opening G-Code.")):
  9054. # Object name
  9055. name = outname or filename.split('/')[-1].split('\\')[-1]
  9056. # New object creation and file processing
  9057. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9058. if obj_ret == 'fail':
  9059. self.inform.emit('[ERROR_NOTCL] %s' %
  9060. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9061. "Try to load it from File menu.\n "
  9062. "Attempting to create a FlatCAM CNCJob Object from "
  9063. "G-Code file failed during processing"))
  9064. return "fail"
  9065. # Register recent file
  9066. self.file_opened.emit("cncjob", filename)
  9067. # GUI feedback
  9068. self.inform.emit('[success] %s: %s' %
  9069. (_("Opened"), filename))
  9070. def open_script(self, filename, outname=None, silent=False):
  9071. """
  9072. Opens a Script file, parses it and creates a new object for
  9073. it in the program. Thread-safe.
  9074. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9075. :param filename: Script file filename
  9076. :type filename: str
  9077. :return: None
  9078. """
  9079. App.log.debug("open_script()")
  9080. with self.proc_container.new(_("Opening TCL Script...")):
  9081. try:
  9082. with open(filename, "r") as opened_script:
  9083. script_content = opened_script.readlines()
  9084. script_content = ''.join(script_content)
  9085. if silent is False:
  9086. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9087. except Exception as e:
  9088. log.debug("App.open_script() -> %s" % str(e))
  9089. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9090. return
  9091. # Object name
  9092. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9093. # New object creation and file processing
  9094. self.on_filenewscript(name=script_name, text=script_content)
  9095. # Register recent file
  9096. self.file_opened.emit("script", filename)
  9097. # GUI feedback
  9098. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9099. def open_config_file(self, filename, run_from_arg=None):
  9100. """
  9101. Loads a config file from the specified file.
  9102. :param filename: Name of the file from which to load.
  9103. :type filename: str
  9104. :return: None
  9105. """
  9106. App.log.debug("Opening config file: " + filename)
  9107. if run_from_arg:
  9108. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9109. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9110. _("Opening FlatCAM Config file.")),
  9111. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9112. color=QtGui.QColor("gray"))
  9113. # # add the tab if it was closed
  9114. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9115. # # first clear previous text in text editor (if any)
  9116. # self.ui.text_editor_tab.code_editor.clear()
  9117. #
  9118. # # Switch plot_area to CNCJob tab
  9119. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9120. # close the Code editor if already open
  9121. if self.toggle_codeeditor:
  9122. self.on_toggle_code_editor()
  9123. self.on_toggle_code_editor()
  9124. try:
  9125. if filename:
  9126. f = QtCore.QFile(filename)
  9127. if f.open(QtCore.QIODevice.ReadOnly):
  9128. stream = QtCore.QTextStream(f)
  9129. code_edited = stream.readAll()
  9130. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9131. f.close()
  9132. except IOError:
  9133. App.log.error("Failed to open config file: %s" % filename)
  9134. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9135. (_("Failed to open config file"), filename))
  9136. return
  9137. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9138. """
  9139. Loads a project from the specified file.
  9140. 1) Loads and parses file
  9141. 2) Registers the file as recently opened.
  9142. 3) Calls on_file_new()
  9143. 4) Updates options
  9144. 5) Calls new_object() with the object's from_dict() as init method.
  9145. 6) Calls plot_all() if plot=True
  9146. :param filename: Name of the file from which to load.
  9147. :type filename: str
  9148. :param run_from_arg: True if run for arguments
  9149. :param plot: If True plot all objects in the project
  9150. :param cli: run from command line
  9151. :return: None
  9152. """
  9153. App.log.debug("Opening project: " + filename)
  9154. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9155. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9156. if cli is None:
  9157. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9158. if run_from_arg:
  9159. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9160. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9161. _("Opening FlatCAM Project file.")),
  9162. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9163. color=QtGui.QColor("gray"))
  9164. # Open and parse an uncompressed Project file
  9165. try:
  9166. f = open(filename, 'r')
  9167. except IOError:
  9168. App.log.error("Failed to open project file: %s" % filename)
  9169. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9170. (_("Failed to open project file"), filename))
  9171. return
  9172. try:
  9173. d = json.load(f, object_hook=dict2obj)
  9174. except Exception as e:
  9175. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9176. (filename, str(e)))
  9177. f.close()
  9178. # Open and parse a compressed Project file
  9179. try:
  9180. with lzma.open(filename) as f:
  9181. file_content = f.read().decode('utf-8')
  9182. d = json.loads(file_content, object_hook=dict2obj)
  9183. except Exception as e:
  9184. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9185. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9186. (_("Failed to open project file"), filename))
  9187. return
  9188. # Clear the current project
  9189. # # NOT THREAD SAFE # ##
  9190. if run_from_arg is True:
  9191. pass
  9192. elif cli is True:
  9193. self.delete_selection_shape()
  9194. else:
  9195. self.on_file_new()
  9196. # Project options
  9197. self.options.update(d['options'])
  9198. self.project_filename = filename
  9199. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9200. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9201. if cli is None:
  9202. self.set_screen_units(self.options["units"])
  9203. # Re create objects
  9204. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9205. for obj in d['objs']:
  9206. def obj_init(obj_inst, app_inst):
  9207. obj_inst.from_dict(obj)
  9208. App.log.debug("Recreating from opened project an %s object: %s" %
  9209. (obj['kind'].capitalize(), obj['options']['name']))
  9210. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9211. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9212. if cli is None:
  9213. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9214. obj['kind'].upper(),
  9215. obj['options']['name']
  9216. )
  9217. )
  9218. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9219. self.inform.emit('[success] %s: %s' %
  9220. (_("Project loaded from"), filename))
  9221. self.should_we_save = False
  9222. self.file_opened.emit("project", filename)
  9223. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9224. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9225. if cli is None:
  9226. self.set_ui_title(name=self.project_filename)
  9227. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9228. def propagate_defaults(self, silent=False):
  9229. """
  9230. This method is used to set default values in classes. It's
  9231. an alternative to project options but allows the use
  9232. of values invisible to the user.
  9233. :return: None
  9234. """
  9235. if silent is False:
  9236. self.log.debug("propagate_defaults()")
  9237. # Which objects to update the given parameters.
  9238. routes = {
  9239. "global_zdownrate": CNCjob,
  9240. "excellon_zeros": Excellon,
  9241. "excellon_format_upper_in": Excellon,
  9242. "excellon_format_lower_in": Excellon,
  9243. "excellon_format_upper_mm": Excellon,
  9244. "excellon_format_lower_mm": Excellon,
  9245. "excellon_units": Excellon,
  9246. "gerber_use_buffer_for_union": Gerber,
  9247. "geometry_multidepth": Geometry
  9248. }
  9249. for param in routes:
  9250. if param in routes[param].defaults:
  9251. try:
  9252. routes[param].defaults[param] = self.defaults[param]
  9253. if silent is False:
  9254. self.log.debug(" " + param + " OK")
  9255. except KeyError:
  9256. if silent is False:
  9257. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9258. else:
  9259. # Try extracting the name:
  9260. # classname_param here is param in the object
  9261. if param.find(routes[param].__name__.lower() + "_") == 0:
  9262. p = param[len(routes[param].__name__) + 1:]
  9263. if p in routes[param].defaults:
  9264. routes[param].defaults[p] = self.defaults[param]
  9265. if silent is False:
  9266. self.log.debug(" " + param + " OK!")
  9267. def plot_all(self, zoom=True):
  9268. """
  9269. Re-generates all plots from all objects.
  9270. :return: None
  9271. """
  9272. self.log.debug("Plot_all()")
  9273. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9274. for obj in self.collection.get_list():
  9275. def worker_task(obj):
  9276. with self.proc_container.new("Plotting"):
  9277. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9278. if zoom:
  9279. self.object_plotted.emit(obj)
  9280. # Send to worker
  9281. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9282. def register_folder(self, filename):
  9283. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9284. def register_save_folder(self, filename):
  9285. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9286. def set_progress_bar(self, percentage, text=""):
  9287. self.ui.progress_bar.setValue(int(percentage))
  9288. def setup_shell(self):
  9289. """
  9290. Creates shell functions. Runs once at startup.
  9291. :return: None
  9292. """
  9293. self.log.debug("setup_shell()")
  9294. def shelp(p=None):
  9295. if not p:
  9296. return _("Available commands:\n") + \
  9297. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9298. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9299. if p not in commands:
  9300. return "Unknown command: %s" % p
  9301. return commands[p]["help"]
  9302. # --- Migrated to new architecture ---
  9303. # def options(name):
  9304. # ops = self.collection.get_by_name(str(name)).options
  9305. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9306. def h(*args):
  9307. """
  9308. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9309. and standalone parameters into list.
  9310. """
  9311. kwa = {}
  9312. a = []
  9313. n = len(args)
  9314. name = None
  9315. for i in range(n):
  9316. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9317. if match:
  9318. assert name is None
  9319. name = match.group(1)
  9320. continue
  9321. if name is None:
  9322. a.append(args[i])
  9323. else:
  9324. kwa[name] = args[i]
  9325. name = None
  9326. return a, kwa
  9327. @contextmanager
  9328. def wait_signal(signal, timeout=10000):
  9329. """
  9330. Block loop until signal emitted, timeout (ms) elapses
  9331. or unhandled exception happens in a thread.
  9332. :param timeout: time after which the loop is exited
  9333. :param signal: Signal to wait for.
  9334. """
  9335. loop = QtCore.QEventLoop()
  9336. # Normal termination
  9337. signal.connect(loop.quit)
  9338. # Termination by exception in thread
  9339. self.thread_exception.connect(loop.quit)
  9340. status = {'timed_out': False}
  9341. def report_quit():
  9342. status['timed_out'] = True
  9343. loop.quit()
  9344. yield
  9345. # Temporarily change how exceptions are managed.
  9346. oeh = sys.excepthook
  9347. ex = []
  9348. def except_hook(type_, value, traceback_):
  9349. ex.append(value)
  9350. oeh(type_, value, traceback_)
  9351. sys.excepthook = except_hook
  9352. # Terminate on timeout
  9353. if timeout is not None:
  9354. QtCore.QTimer.singleShot(timeout, report_quit)
  9355. # # ## Block ## ##
  9356. loop.exec_()
  9357. # Restore exception management
  9358. sys.excepthook = oeh
  9359. if ex:
  9360. self.raiseTclError(str(ex[0]))
  9361. if status['timed_out']:
  9362. raise Exception('Timed out!')
  9363. def make_docs():
  9364. output = ''
  9365. import collections
  9366. od = collections.OrderedDict(sorted(commands.items()))
  9367. for cmd_, val in od.items():
  9368. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9369. t = val['help']
  9370. usage_i = t.find('>')
  9371. if usage_i < 0:
  9372. expl = t
  9373. output += expl + '\n\n'
  9374. continue
  9375. expl = t[:usage_i - 1]
  9376. output += expl + '\n\n'
  9377. end_usage_i = t[usage_i:].find('\n')
  9378. if end_usage_i < 0:
  9379. end_usage_i = len(t[usage_i:])
  9380. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9381. else:
  9382. extras = t[usage_i+end_usage_i+1:]
  9383. parts = [s.strip() for s in extras.split('\n')]
  9384. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9385. for p in parts:
  9386. output += ' ' + p + '\n\n'
  9387. return output
  9388. '''
  9389. Howto implement TCL shell commands:
  9390. All parameters passed to command should be possible to set as None and test it afterwards.
  9391. This is because we need to see error caused in tcl,
  9392. if None value as default parameter is not allowed TCL will return empty error.
  9393. Use:
  9394. def mycommand(name=None,...):
  9395. Test it like this:
  9396. if name is None:
  9397. self.raise_tcl_error('Argument name is missing.')
  9398. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9399. otherwise we will miss it and processing will silently continue.
  9400. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9401. which is catched in exec_command and displayed in TCL shell console with red background.
  9402. Error in console is displayed with TCL trace.
  9403. This behavior works only within main thread,
  9404. errors with promissed tasks can be catched and detected only with log.
  9405. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9406. TCL shell.
  9407. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9408. '''
  9409. commands = {
  9410. 'help': {
  9411. 'fcn': shelp,
  9412. 'help': _("Shows list of commands.")
  9413. },
  9414. }
  9415. # Import/overwrite tcl commands as objects of TclCommand descendants
  9416. # This modifies the variable 'commands'.
  9417. tclCommands.register_all_commands(self, commands)
  9418. # Add commands to the tcl interpreter
  9419. for cmd in commands:
  9420. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9421. # Make the tcl puts function return instead of print to stdout
  9422. self.tcl.eval('''
  9423. rename puts original_puts
  9424. proc puts {args} {
  9425. if {[llength $args] == 1} {
  9426. return "[lindex $args 0]"
  9427. } else {
  9428. eval original_puts $args
  9429. }
  9430. }
  9431. ''')
  9432. def setup_recent_items(self):
  9433. # TODO: Move this to constructor
  9434. icons = {
  9435. "gerber": "share/flatcam_icon16.png",
  9436. "excellon": "share/drill16.png",
  9437. 'geometry': "share/geometry16.png",
  9438. "cncjob": "share/cnc16.png",
  9439. "script": "share/script_new24.png",
  9440. "document": "share/notes16_1.png",
  9441. "project": "share/project16.png",
  9442. "svg": "share/geometry16.png",
  9443. "dxf": "share/dxf16.png",
  9444. "pdf": "share/pdf32.png",
  9445. "image": "share/image16.png"
  9446. }
  9447. openers = {
  9448. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9449. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9450. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9451. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9452. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9453. "document": None,
  9454. 'project': self.open_project,
  9455. 'svg': self.import_svg,
  9456. 'dxf': self.import_dxf,
  9457. 'image': self.image_tool.import_image,
  9458. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9459. }
  9460. # Open recent file for files
  9461. try:
  9462. f = open(self.data_path + '/recent.json')
  9463. except IOError:
  9464. App.log.error("Failed to load recent item list.")
  9465. self.inform.emit('[ERROR_NOTCL] %s' %
  9466. _("Failed to load recent item list."))
  9467. return
  9468. try:
  9469. self.recent = json.load(f)
  9470. except json.scanner.JSONDecodeError:
  9471. App.log.error("Failed to parse recent item list.")
  9472. self.inform.emit('[ERROR_NOTCL] %s' %
  9473. _("Failed to parse recent item list."))
  9474. f.close()
  9475. return
  9476. f.close()
  9477. # Open recent file for projects
  9478. try:
  9479. fp = open(self.data_path + '/recent_projects.json')
  9480. except IOError:
  9481. App.log.error("Failed to load recent project item list.")
  9482. self.inform.emit('[ERROR_NOTCL] %s' %
  9483. _("Failed to load recent projects item list."))
  9484. return
  9485. try:
  9486. self.recent_projects = json.load(fp)
  9487. except json.scanner.JSONDecodeError:
  9488. App.log.error("Failed to parse recent project item list.")
  9489. self.inform.emit('[ERROR_NOTCL] %s' %
  9490. _("Failed to parse recent project item list."))
  9491. fp.close()
  9492. return
  9493. fp.close()
  9494. # Closure needed to create callbacks in a loop.
  9495. # Otherwise late binding occurs.
  9496. def make_callback(func, fname):
  9497. def opener():
  9498. func(fname)
  9499. return opener
  9500. def reset_recent_files():
  9501. # Reset menu
  9502. self.ui.recent.clear()
  9503. self.recent = []
  9504. try:
  9505. ff = open(self.data_path + '/recent.json', 'w')
  9506. except IOError:
  9507. App.log.error("Failed to open recent items file for writing.")
  9508. return
  9509. json.dump(self.recent, ff)
  9510. def reset_recent_projects():
  9511. # Reset menu
  9512. self.ui.recent_projects.clear()
  9513. self.recent_projects = []
  9514. try:
  9515. fp = open(self.data_path + '/recent_projects.json', 'w')
  9516. except IOError:
  9517. App.log.error("Failed to open recent projects items file for writing.")
  9518. return
  9519. json.dump(self.recent, fp)
  9520. # Reset menu
  9521. self.ui.recent.clear()
  9522. self.ui.recent_projects.clear()
  9523. # Create menu items for projects
  9524. for recent in self.recent_projects:
  9525. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9526. if recent['kind'] == 'project':
  9527. try:
  9528. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9529. # Attach callback
  9530. o = make_callback(openers[recent["kind"]], recent['filename'])
  9531. action.triggered.connect(o)
  9532. self.ui.recent_projects.addAction(action)
  9533. except KeyError:
  9534. App.log.error("Unsupported file type: %s" % recent["kind"])
  9535. # Last action in Recent Files menu is one that Clear the content
  9536. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9537. clear_action_proj.triggered.connect(reset_recent_projects)
  9538. self.ui.recent_projects.addSeparator()
  9539. self.ui.recent_projects.addAction(clear_action_proj)
  9540. # Create menu items for files
  9541. for recent in self.recent:
  9542. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9543. if recent['kind'] != 'project':
  9544. try:
  9545. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9546. # Attach callback
  9547. o = make_callback(openers[recent["kind"]], recent['filename'])
  9548. action.triggered.connect(o)
  9549. self.ui.recent.addAction(action)
  9550. except KeyError:
  9551. App.log.error("Unsupported file type: %s" % recent["kind"])
  9552. # Last action in Recent Files menu is one that Clear the content
  9553. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9554. clear_action.triggered.connect(reset_recent_files)
  9555. self.ui.recent.addSeparator()
  9556. self.ui.recent.addAction(clear_action)
  9557. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9558. # self.ui.menufilerecent.set_submenu(recent_menu)
  9559. # recent_menu.show_all()
  9560. # self.ui.recent.show()
  9561. self.log.debug("Recent items list has been populated.")
  9562. def setup_component_editor(self):
  9563. # label = QtWidgets.QLabel("Choose an item from Project")
  9564. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9565. sel_title = QtWidgets.QTextEdit(
  9566. _('<b>Shortcut Key List</b>'))
  9567. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9568. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9569. settings = QSettings("Open Source", "FlatCAM")
  9570. if settings.contains("notebook_font_size"):
  9571. fsize = settings.value('notebook_font_size', type=int)
  9572. else:
  9573. fsize = 12
  9574. tsize = fsize + int(fsize / 2)
  9575. # selected_text = (_('''
  9576. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9577. #
  9578. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9579. # The normal flow when working in FlatCAM is the following:</span></p>
  9580. #
  9581. # <ol>
  9582. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9583. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9584. # even dragging and dropping the files on the GUI.<br />
  9585. # <br />
  9586. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9587. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9588. # &nbsp;</li>
  9589. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9590. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9591. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9592. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9593. # <br />
  9594. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9595. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9596. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9597. # it even if it was out of focus.<br />
  9598. # <br />
  9599. # You can change the parameters in this screen and the flow direction is like this:<br />
  9600. # <br />
  9601. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9602. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9603. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9604. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9605. # </ol>
  9606. #
  9607. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9608. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9609. # <strong>F3</strong>.</span></p>
  9610. #
  9611. # ''').format(fsize=fsize, tsize=tsize))
  9612. selected_text = '''
  9613. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9614. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9615. {s1}</span></p>
  9616. <ol>
  9617. <li><span style="font-size:{fsize}px">{s2}<br />
  9618. <br />
  9619. {s3}</span><br />
  9620. &nbsp;</li>
  9621. <li><span style="font-size:{fsize}px">{s4}<br />
  9622. &nbsp;</li>
  9623. <br />
  9624. <li><span style="font-size:{fsize}px">{s5}<br />
  9625. &nbsp;</li>
  9626. <br />
  9627. <li><span style="font-size:{fsize}px">{s6}<br />
  9628. <br />
  9629. {s7}</span></li>
  9630. </ol>
  9631. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9632. '''.format(
  9633. title=_("Selected Tab - Choose an Item from Project Tab"),
  9634. subtitle=_("Details"),
  9635. s1=_("The normal flow when working in FlatCAM is the following:"),
  9636. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9637. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9638. "files on the GUI."),
  9639. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9640. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9641. "actions offered within the app."),
  9642. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9643. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9644. "SELECTED TAB will be updated with the object properties according to its kind: "
  9645. "Gerber, Excellon, Geometry or CNCJob object."),
  9646. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9647. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9648. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9649. "the SELECTED TAB and populate it even if it was out of focus."),
  9650. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9651. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9652. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9653. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9654. "(again, done in SELECTED TAB) --> Save GCode."),
  9655. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9656. "or through its own key shortcut: <b>F3</b>."),
  9657. tsize=tsize,
  9658. fsize=fsize
  9659. )
  9660. sel_title.setText(selected_text)
  9661. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9662. self.ui.selected_scroll_area.setWidget(sel_title)
  9663. def setup_obj_classes(self):
  9664. """
  9665. Sets up application specifics on the FlatCAMObj class.
  9666. :return: None
  9667. """
  9668. FlatCAMObj.app = self
  9669. ObjectCollection.app = self
  9670. Gerber.app = self
  9671. Excellon.app = self
  9672. Geometry.app = self
  9673. CNCjob.app = self
  9674. FCProcess.app = self
  9675. FCProcessContainer.app = self
  9676. def version_check(self):
  9677. """
  9678. Checks for the latest version of the program. Alerts the
  9679. user if theirs is outdated. This method is meant to be run
  9680. in a separate thread.
  9681. :return: None
  9682. """
  9683. self.log.debug("version_check()")
  9684. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9685. full_url = App.version_url + \
  9686. "?s=" + str(self.defaults['global_serial']) + \
  9687. "&v=" + str(self.version) + \
  9688. "&os=" + str(self.os) + \
  9689. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9690. else:
  9691. # no_stats dict; just so it won't break things on website
  9692. no_ststs_dict = {}
  9693. no_ststs_dict["global_ststs"] = {}
  9694. full_url = App.version_url + \
  9695. "?s=" + str(self.defaults['global_serial']) + \
  9696. "&v=" + str(self.version) + \
  9697. "&os=" + str(self.os) + \
  9698. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9699. App.log.debug("Checking for updates @ %s" % full_url)
  9700. # ## Get the data
  9701. try:
  9702. f = urllib.request.urlopen(full_url)
  9703. except Exception:
  9704. # App.log.warning("Failed checking for latest version. Could not connect.")
  9705. self.log.warning("Failed checking for latest version. Could not connect.")
  9706. self.inform.emit('[WARNING_NOTCL] %s' %
  9707. _("Failed checking for latest version. Could not connect."))
  9708. return
  9709. try:
  9710. data = json.load(f)
  9711. except Exception as e:
  9712. App.log.error("Could not parse information about latest version.")
  9713. self.inform.emit('[ERROR_NOTCL] %s' %
  9714. _("Could not parse information about latest version."))
  9715. App.log.debug("json.load(): %s" % str(e))
  9716. f.close()
  9717. return
  9718. f.close()
  9719. # ## Latest version?
  9720. if self.version >= data["version"]:
  9721. App.log.debug("FlatCAM is up to date!")
  9722. self.inform.emit('[success] %s' %
  9723. _("FlatCAM is up to date!"))
  9724. return
  9725. App.log.debug("Newer version available.")
  9726. self.message.emit(
  9727. _("Newer Version Available"),
  9728. _("There is a newer version of FlatCAM available for download:\n\n") +
  9729. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9730. _("info")
  9731. )
  9732. def on_plotcanvas_setup(self, container=None):
  9733. """
  9734. This is doing the setup for the plot area (VisPy canvas)
  9735. :param container: widget where to install the canvas
  9736. :return: None
  9737. """
  9738. if container:
  9739. plot_container = container
  9740. else:
  9741. plot_container = self.ui.right_layout
  9742. if self.is_legacy is False:
  9743. self.plotcanvas = PlotCanvas(plot_container, self)
  9744. else:
  9745. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9746. # So it can receive key presses
  9747. self.plotcanvas.native.setFocus()
  9748. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9749. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9750. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9751. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9752. # Keys over plot enabled
  9753. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9754. if self.defaults['global_cursor_type'] == 'small':
  9755. self.app_cursor = self.plotcanvas.new_cursor()
  9756. else:
  9757. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9758. if self.ui.grid_snap_btn.isChecked():
  9759. self.app_cursor.enabled = True
  9760. else:
  9761. self.app_cursor.enabled = False
  9762. if self.is_legacy is False:
  9763. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9764. else:
  9765. # will use the default Matplotlib axes
  9766. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9767. def on_zoom_fit(self, event):
  9768. """
  9769. Callback for zoom-out request. This can be either from the corresponding
  9770. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9771. with axes limits from the geometry bounds of all objects.
  9772. :param event: Ignored.
  9773. :return: None
  9774. """
  9775. if self.is_legacy is False:
  9776. self.plotcanvas.fit_view()
  9777. else:
  9778. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9779. width = xmax - xmin
  9780. height = ymax - ymin
  9781. xmin -= 0.05 * width
  9782. xmax += 0.05 * width
  9783. ymin -= 0.05 * height
  9784. ymax += 0.05 * height
  9785. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9786. def on_zoom_in(self):
  9787. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9788. def on_zoom_out(self):
  9789. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9790. def disable_all_plots(self):
  9791. self.report_usage("disable_all_plots()")
  9792. self.disable_plots(self.collection.get_list())
  9793. self.inform.emit('[success] %s' %
  9794. _("All plots disabled."))
  9795. def disable_other_plots(self):
  9796. self.report_usage("disable_other_plots()")
  9797. self.disable_plots(self.collection.get_non_selected())
  9798. self.inform.emit('[success] %s' %
  9799. _("All non selected plots disabled."))
  9800. def enable_all_plots(self):
  9801. self.report_usage("enable_all_plots()")
  9802. self.enable_plots(self.collection.get_list())
  9803. self.inform.emit('[success] %s' %
  9804. _("All plots enabled."))
  9805. def on_enable_sel_plots(self):
  9806. log.debug("App.on_enable_sel_plot()")
  9807. object_list = self.collection.get_selected()
  9808. self.enable_plots(objects=object_list)
  9809. self.inform.emit('[success] %s' %
  9810. _("Selected plots enabled..."))
  9811. def on_disable_sel_plots(self):
  9812. log.debug("App.on_disable_sel_plot()")
  9813. # self.inform.emit(_("Disabling plots ..."))
  9814. object_list = self.collection.get_selected()
  9815. self.disable_plots(objects=object_list)
  9816. self.inform.emit('[success] %s' %
  9817. _("Selected plots disabled..."))
  9818. def enable_plots(self, objects):
  9819. """
  9820. Disables plots
  9821. :param objects: list of Objects to be enabled
  9822. :return:
  9823. """
  9824. log.debug("Enabling plots ...")
  9825. # self.inform.emit(_("Working ..."))
  9826. for obj in objects:
  9827. if obj.options['plot'] is False:
  9828. obj.options.set_change_callback(lambda x: None)
  9829. obj.options['plot'] = True
  9830. obj.options.set_change_callback(obj.on_options_change)
  9831. def worker_task(objs):
  9832. with self.proc_container.new(_("Enabling plots ...")):
  9833. for obj in objs:
  9834. # obj.options['plot'] = True
  9835. if isinstance(obj, FlatCAMCNCjob):
  9836. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9837. else:
  9838. obj.plot(visible=True)
  9839. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9840. # self.plots_updated.emit()
  9841. def disable_plots(self, objects):
  9842. """
  9843. Disables plots
  9844. :param objects: list of Objects to be disabled
  9845. :return:
  9846. """
  9847. # if no objects selected then do nothing
  9848. if not self.collection.get_selected():
  9849. return
  9850. log.debug("Disabling plots ...")
  9851. # self.inform.emit(_("Working ..."))
  9852. for obj in objects:
  9853. if obj.options['plot'] is True:
  9854. obj.options.set_change_callback(lambda x: None)
  9855. obj.options['plot'] = False
  9856. obj.options.set_change_callback(obj.on_options_change)
  9857. try:
  9858. self.delete_selection_shape()
  9859. except Exception as e:
  9860. log.debug("App.disable_plots() --> %s" % str(e))
  9861. # self.plots_updated.emit()
  9862. def worker_task(objs):
  9863. with self.proc_container.new(_("Disabling plots ...")):
  9864. for obj in objs:
  9865. # obj.options['plot'] = True
  9866. if isinstance(obj, FlatCAMCNCjob):
  9867. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9868. else:
  9869. obj.plot(visible=False)
  9870. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9871. def toggle_plots(self, objects):
  9872. """
  9873. Toggle plots visibility
  9874. :param objects: list of Objects for which to be toggled the visibility
  9875. :return:
  9876. """
  9877. # if no objects selected then do nothing
  9878. if not self.collection.get_selected():
  9879. return
  9880. log.debug("Toggling plots ...")
  9881. self.inform.emit(_("Working ..."))
  9882. for obj in objects:
  9883. if obj.options['plot'] is False:
  9884. obj.options['plot'] = True
  9885. else:
  9886. obj.options['plot'] = False
  9887. self.plots_updated.emit()
  9888. def clear_plots(self):
  9889. objects = self.collection.get_list()
  9890. for obj in objects:
  9891. obj.clear(obj == objects[-1])
  9892. # Clear pool to free memory
  9893. self.clear_pool()
  9894. def generate_cnc_job(self, objects):
  9895. self.report_usage("generate_cnc_job()")
  9896. # for obj in objects:
  9897. # obj.generatecncjob()
  9898. for obj in objects:
  9899. obj.on_generatecnc_button_click()
  9900. def save_project(self, filename, quit_action=False, silent=False):
  9901. """
  9902. Saves the current project to the specified file.
  9903. :param filename: Name of the file in which to save.
  9904. :type filename: str
  9905. :param quit_action: if the project saving will be followed by an app quit; boolean
  9906. :param silent: if True will not display status messages
  9907. :return: None
  9908. """
  9909. self.log.debug("save_project()")
  9910. self.save_in_progress = True
  9911. with self.proc_container.new(_("Saving FlatCAM Project")):
  9912. # Capture the latest changes
  9913. # Current object
  9914. try:
  9915. self.collection.get_active().read_form()
  9916. except Exception as e:
  9917. self.log.debug("There was no active object. %s" % str(e))
  9918. pass
  9919. # Serialize the whole project
  9920. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9921. "options": self.options,
  9922. "version": self.version}
  9923. if self.defaults["global_save_compressed"] is True:
  9924. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9925. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9926. # # Write
  9927. f.write(g)
  9928. self.inform.emit('[success] %s: %s' %
  9929. (_("Project saved to"), filename))
  9930. else:
  9931. # Open file
  9932. try:
  9933. f = open(filename, 'w')
  9934. except IOError:
  9935. App.log.error("Failed to open file for saving: %s", filename)
  9936. return
  9937. # Write
  9938. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9939. f.close()
  9940. # verification of the saved project
  9941. # Open and parse
  9942. try:
  9943. saved_f = open(filename, 'r')
  9944. except IOError:
  9945. if silent is False:
  9946. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9947. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9948. )
  9949. return
  9950. try:
  9951. saved_d = json.load(saved_f, object_hook=dict2obj)
  9952. except Exception:
  9953. if silent is False:
  9954. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9955. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9956. )
  9957. f.close()
  9958. return
  9959. saved_f.close()
  9960. if silent is False:
  9961. if 'version' in saved_d:
  9962. self.inform.emit('[success] %s: %s' %
  9963. (_("Project saved to"), filename))
  9964. else:
  9965. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9966. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9967. )
  9968. tb_settings = QSettings("Open Source", "FlatCAM")
  9969. lock_state = self.ui.lock_action.isChecked()
  9970. tb_settings.setValue('toolbar_lock', lock_state)
  9971. # This will write the setting to the platform specific storage.
  9972. del tb_settings
  9973. # if quit:
  9974. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9975. # t.start()
  9976. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9977. def start_delayed_quit(self, delay, filename, should_quit=None):
  9978. """
  9979. :param delay: period of checking if project file size is more than zero; in seconds
  9980. :param filename: the name of the project file to be checked periodically for size more than zero
  9981. :param should_quit: if the task finished will be followed by an app quit; boolean
  9982. :return:
  9983. """
  9984. to_quit = should_quit
  9985. self.save_timer = QtCore.QTimer()
  9986. self.save_timer.setInterval(delay)
  9987. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9988. self.save_timer.start()
  9989. def check_project_file_size(self, filename, should_quit=None):
  9990. """
  9991. :param filename: the name of the project file to be checked periodically for size more than zero
  9992. :param should_quit: will quit the app if True; boolean
  9993. :return:
  9994. """
  9995. try:
  9996. if os.stat(filename).st_size > 0:
  9997. self.save_in_progress = False
  9998. self.save_timer.stop()
  9999. if should_quit:
  10000. self.app_quit.emit()
  10001. except Exception:
  10002. traceback.print_exc()
  10003. def on_plotarea_tab_closed(self, tab_idx):
  10004. widget = self.ui.plot_tab_area.widget(tab_idx)
  10005. if widget is not None:
  10006. widget.deleteLater()
  10007. self.ui.plot_tab_area.removeTab(tab_idx)
  10008. def on_options_app2project(self):
  10009. """
  10010. Callback for Options->Transfer Options->App=>Project. Copies options
  10011. from application defaults to project defaults.
  10012. :return: None
  10013. """
  10014. self.report_usage("on_options_app2project")
  10015. self.defaults_read_form()
  10016. self.options.update(self.defaults)
  10017. # self.options_write_form()
  10018. class ArgsThread(QtCore.QObject):
  10019. open_signal = pyqtSignal(list)
  10020. start = pyqtSignal()
  10021. if sys.platform == 'win32':
  10022. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10023. else:
  10024. address = ('/tmp/testipc', 'AF_UNIX')
  10025. def __init__(self):
  10026. super(ArgsThread, self).__init__()
  10027. self.start.connect(self.run)
  10028. def my_loop(self, address):
  10029. try:
  10030. listener = Listener(*address)
  10031. while True:
  10032. conn = listener.accept()
  10033. self.serve(conn)
  10034. except socket.error:
  10035. conn = Client(*address)
  10036. conn.send(sys.argv)
  10037. conn.send('close')
  10038. # close the current instance only if there are args
  10039. if len(sys.argv) > 1:
  10040. sys.exit()
  10041. def serve(self, conn):
  10042. while True:
  10043. msg = conn.recv()
  10044. if msg == 'close':
  10045. break
  10046. self.open_signal.emit(msg)
  10047. conn.close()
  10048. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10049. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10050. @pyqtSlot()
  10051. def run(self):
  10052. self.my_loop(self.address)
  10053. class GracefulException(Exception):
  10054. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10055. def __init__(self):
  10056. super().__init__()
  10057. def __str__(self):
  10058. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10059. # end of file