FlatCAMApp.py 446 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import winreg
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool
  28. import socket
  29. from array import array
  30. # #######################################
  31. # # Imports part of FlatCAM ##
  32. # #######################################
  33. from ObjectCollection import *
  34. from FlatCAMObj import *
  35. from flatcamGUI.PlotCanvas import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. if '_' not in builtins.__dict__:
  54. _ = gettext.gettext
  55. # ########################################
  56. # # App ###
  57. # ########################################
  58. class App(QtCore.QObject):
  59. """
  60. The main application class. The constructor starts the GUI.
  61. """
  62. # Get Cmd Line Options
  63. cmd_line_shellfile = ''
  64. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  65. try:
  66. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  67. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  68. except getopt.GetoptError:
  69. print(cmd_line_help)
  70. sys.exit(2)
  71. for opt, arg in cmd_line_options:
  72. if opt == '-h':
  73. print(cmd_line_help)
  74. sys.exit()
  75. elif opt == '--shellfile':
  76. cmd_line_shellfile = arg
  77. # ## Logging ###
  78. log = logging.getLogger('base')
  79. log.setLevel(logging.DEBUG)
  80. # log.setLevel(logging.WARNING)
  81. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  82. handler = logging.StreamHandler()
  83. handler.setFormatter(formatter)
  84. log.addHandler(handler)
  85. # ##########################################################################
  86. # ################## Version and VERSION DATE ##############################
  87. # ##########################################################################
  88. version = 8.97
  89. version_date = "2019/09/09"
  90. beta = True
  91. # current date now
  92. date = str(datetime.today()).rpartition('.')[0]
  93. date = ''.join(c for c in date if c not in ':-')
  94. date = date.replace(' ', '_')
  95. # URL for update checks and statistics
  96. version_url = "http://flatcam.org/version"
  97. # App URL
  98. app_url = "http://flatcam.org"
  99. # Manual URL
  100. manual_url = "http://flatcam.org/manual/index.html"
  101. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  102. # this variable will hold the project status
  103. # if True it will mean that the project was modified and not saved
  104. should_we_save = False
  105. # flag is True if saving action has been triggered
  106. save_in_progress = False
  107. # ###########################################################################
  108. # ############################# Signals ################################
  109. # ###########################################################################
  110. # Inform the user
  111. # Handled by:
  112. # * App.info() --> Print on the status bar
  113. inform = QtCore.pyqtSignal(str)
  114. app_quit = QtCore.pyqtSignal()
  115. # General purpose background task
  116. worker_task = QtCore.pyqtSignal(dict)
  117. # File opened
  118. # Handled by:
  119. # * register_folder()
  120. # * register_recent()
  121. # Note: Setting the parameters to unicode does not seem
  122. # to have an effect. Then are received as Qstring
  123. # anyway.
  124. # File type and filename
  125. file_opened = QtCore.pyqtSignal(str, str)
  126. # File type and filename
  127. file_saved = QtCore.pyqtSignal(str, str)
  128. # Percentage of progress
  129. progress = QtCore.pyqtSignal(int)
  130. plots_updated = QtCore.pyqtSignal()
  131. # Emitted by new_object() and passes the new object as argument, plot flag.
  132. # on_object_created() adds the object to the collection, plots on appropriate flag
  133. # and emits new_object_available.
  134. object_created = QtCore.pyqtSignal(object, bool, bool)
  135. # Emitted when a object has been changed (like scaled, mirrored)
  136. object_changed = QtCore.pyqtSignal(object)
  137. # Emitted after object has been plotted.
  138. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  139. object_plotted = QtCore.pyqtSignal(object)
  140. # Emitted when a new object has been added or deleted from/to the collection
  141. object_status_changed = QtCore.pyqtSignal(object, str)
  142. message = QtCore.pyqtSignal(str, str, str)
  143. # Emmited when shell command is finished(one command only)
  144. shell_command_finished = QtCore.pyqtSignal(object)
  145. # Emitted when multiprocess pool has been recreated
  146. pool_recreated = QtCore.pyqtSignal(object)
  147. # Emitted when an unhandled exception happens
  148. # in the worker task.
  149. thread_exception = QtCore.pyqtSignal(object)
  150. # used to signal that there are arguments for the app
  151. args_at_startup = QtCore.pyqtSignal(list)
  152. # a reusable signal to replot a list of objects
  153. # should be disconnected after use so it can be reused
  154. replot_signal = pyqtSignal(list)
  155. def __init__(self, user_defaults=True, post_gui=None):
  156. """
  157. Starts the application.
  158. :return: app
  159. :rtype: App
  160. """
  161. App.log.info("FlatCAM Starting...")
  162. self.main_thread = QtWidgets.QApplication.instance().thread()
  163. # ############################################################################
  164. # # ################# OS-specific ############################################
  165. # ############################################################################
  166. portable = False
  167. # Folder for user settings.
  168. if sys.platform == 'win32':
  169. # #########################################################################
  170. # Setup the listening thread for another instance launching with args #####
  171. # #########################################################################
  172. # make sure the thread is stored by using a self. otherwise it's garbage collected
  173. self.th = QtCore.QThread()
  174. self.th.start(priority=QtCore.QThread.LowestPriority)
  175. self.new_launch = ArgsThread()
  176. self.new_launch.open_signal[list].connect(self.on_startup_args)
  177. self.new_launch.moveToThread(self.th)
  178. self.new_launch.start.emit()
  179. from win32com.shell import shell, shellcon
  180. if platform.architecture()[0] == '32bit':
  181. App.log.debug("Win32!")
  182. else:
  183. App.log.debug("Win64!")
  184. # #########################################################################
  185. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  186. # #########################################################################
  187. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  188. try:
  189. with open(config_file, 'r') as f:
  190. try:
  191. for line in f:
  192. param = str(line).rpartition('=')
  193. if param[0] == 'portable':
  194. try:
  195. portable = eval(param[2])
  196. except NameError:
  197. portable = False
  198. except Exception as e:
  199. log.debug('App.__init__() -->%s' % str(e))
  200. return
  201. except FileNotFoundError:
  202. pass
  203. if portable is False:
  204. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  205. else:
  206. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  207. self.os = 'windows'
  208. else: # Linux/Unix/MacOS
  209. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  210. self.os = 'unix'
  211. # ##########################################################################
  212. # ################## Setup folders and files ###############################
  213. # ##########################################################################
  214. if not os.path.exists(self.data_path):
  215. os.makedirs(self.data_path)
  216. App.log.debug('Created data folder: ' + self.data_path)
  217. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  218. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  219. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  220. if not os.path.exists(self.postprocessorpaths):
  221. os.makedirs(self.postprocessorpaths)
  222. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  223. # create current_defaults.FlatConfig file if there is none
  224. try:
  225. f = open(self.data_path + '/current_defaults.FlatConfig')
  226. f.close()
  227. except IOError:
  228. App.log.debug('Creating empty current_defaults.FlatConfig')
  229. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  230. json.dump({}, f)
  231. f.close()
  232. # create factory_defaults.FlatConfig file if there is none
  233. try:
  234. f = open(self.data_path + '/factory_defaults.FlatConfig')
  235. f.close()
  236. except IOError:
  237. App.log.debug('Creating empty factory_defaults.FlatConfig')
  238. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  239. json.dump({}, f)
  240. f.close()
  241. try:
  242. f = open(self.data_path + '/recent.json')
  243. f.close()
  244. except IOError:
  245. App.log.debug('Creating empty recent.json')
  246. f = open(self.data_path + '/recent.json', 'w')
  247. json.dump([], f)
  248. f.close()
  249. try:
  250. fp = open(self.data_path + '/recent_projects.json')
  251. fp.close()
  252. except IOError:
  253. App.log.debug('Creating empty recent_projects.json')
  254. fp = open(self.data_path + '/recent_projects.json', 'w')
  255. json.dump([], fp)
  256. fp.close()
  257. # Application directory. CHDIR to it. Otherwise, trying to load
  258. # GUI icons will fail as their path is relative.
  259. # This will fail under cx_freeze ...
  260. self.app_home = os.path.dirname(os.path.realpath(__file__))
  261. App.log.debug("Application path is " + self.app_home)
  262. App.log.debug("Started in " + os.getcwd())
  263. # cx_freeze workaround
  264. if os.path.isfile(self.app_home):
  265. self.app_home = os.path.dirname(self.app_home)
  266. os.chdir(self.app_home)
  267. # #############################################################################
  268. # ##################### CREATE MULTIPROCESSING POOL ###########################
  269. # #############################################################################
  270. self.pool = Pool()
  271. # #############################################################################
  272. # ##################### Initialize GUI ########################################
  273. # #############################################################################
  274. # FlatCAM colors used in plotting
  275. self.FC_light_green = '#BBF268BF'
  276. self.FC_dark_green = '#006E20BF'
  277. self.FC_light_blue = '#a5a5ffbf'
  278. self.FC_dark_blue = '#0000ffbf'
  279. QtCore.QObject.__init__(self)
  280. self.ui = FlatCAMGUI(self.version, self.beta, self)
  281. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  282. self.ui.final_save.connect(self.final_save)
  283. # #############################################################################
  284. # ############################## Data #########################################
  285. # #############################################################################
  286. self.recent = []
  287. self.recent_projects = []
  288. self.clipboard = QtWidgets.QApplication.clipboard()
  289. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  290. self.project_filename = None
  291. self.toggle_units_ignore = False
  292. # self.defaults_form = PreferencesUI()
  293. # when adding entries here read the comments in the method found bellow named:
  294. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  295. self.defaults_form_fields = {
  296. # General App
  297. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  298. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  299. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  300. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  301. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  302. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  303. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  304. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  305. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  306. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  307. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  308. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  309. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  310. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  311. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  312. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  313. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  314. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  315. # General GUI Preferences
  316. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  317. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  318. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  319. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  320. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  321. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  322. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  323. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  324. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  325. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  326. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  327. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  328. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  329. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  330. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  331. # General GUI Settings
  332. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  333. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  334. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  335. # Gerber General
  336. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  337. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  338. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  339. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  340. # Gerber Options
  341. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  342. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  343. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  344. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  345. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  346. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  347. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  348. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  349. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  350. # Gerber Advanced Options
  351. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  352. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  353. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  354. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  355. # Gerber Export
  356. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  357. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  358. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  359. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  360. # Gerber Editor
  361. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  362. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  363. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  364. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  365. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  366. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  367. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  368. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  369. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  370. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  371. "gerber_editor_circ_angle":
  372. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  373. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  374. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  375. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  376. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  377. # Excellon General
  378. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  379. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  380. "excellon_format_upper_in":
  381. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  382. "excellon_format_lower_in":
  383. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  384. "excellon_format_upper_mm":
  385. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  386. "excellon_format_lower_mm":
  387. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  388. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  389. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  390. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  391. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  392. # Excellon Options
  393. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  394. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  395. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  396. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  397. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  398. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  399. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  400. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  401. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  402. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  403. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  404. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  405. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  406. # Excellon Advanced Options
  407. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  408. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  409. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  410. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  411. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  412. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  413. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  414. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  415. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  416. # Excellon Export
  417. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  418. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  419. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  420. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  421. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  422. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  423. # Excellon Editor
  424. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  425. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  426. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  427. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  428. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  429. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  430. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  431. "excellon_editor_circ_angle":
  432. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  433. # Excellon Slots
  434. "excellon_editor_slot_direction":
  435. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  436. "excellon_editor_slot_angle":
  437. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  438. "excellon_editor_slot_length":
  439. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  440. # Excellon Slots
  441. "excellon_editor_slot_array_size":
  442. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  443. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  444. "excellon_editor_slot_lin_pitch":
  445. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  446. "excellon_editor_slot_lin_angle":
  447. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  448. "excellon_editor_slot_circ_dir":
  449. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  450. "excellon_editor_slot_circ_angle":
  451. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  452. # Geometry General
  453. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  454. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  455. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  456. # Geometry Options
  457. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  458. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  459. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  460. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  461. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  462. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  463. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  464. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  465. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  466. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  467. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  468. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  469. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  470. # Geometry Advanced Options
  471. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  472. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  473. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  474. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  475. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  476. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  477. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  478. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  479. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  480. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  481. # Geometry Editor
  482. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  483. # CNCJob General
  484. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  485. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  486. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  487. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  488. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  489. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  490. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  491. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  492. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  493. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  494. # CNC Job Options
  495. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  496. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  497. # CNC Job Advanced Options
  498. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  499. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  500. # NCC Tool
  501. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  502. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  503. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  504. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  505. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  506. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  507. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  508. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  509. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  510. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  511. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  512. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  513. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  514. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  515. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  516. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  517. # CutOut Tool
  518. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  519. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  520. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  521. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  522. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  523. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  524. # Paint Area Tool
  525. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  526. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  527. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  528. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  529. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  530. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  531. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  532. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  533. # 2-sided Tool
  534. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  535. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  536. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  537. # Film Tool
  538. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  539. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  540. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  541. # Panelize Tool
  542. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  543. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  544. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  545. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  546. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  547. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  548. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  549. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  550. # Calculators Tool
  551. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  552. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  553. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  554. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  555. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  556. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  557. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  558. # Transformations Tool
  559. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  560. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  561. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  562. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  563. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  564. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  565. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  566. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  567. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  568. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  569. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  570. # SolderPaste Dispensing Tool
  571. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  572. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  573. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  574. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  575. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  576. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  577. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  578. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  579. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  580. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  581. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  582. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  583. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  584. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  585. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  586. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  587. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  588. # file associations
  589. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  590. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  591. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  592. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  593. }
  594. # ############################
  595. # ### LOAD POSTPROCESSORS ####
  596. # ############################
  597. self.postprocessors = load_postprocessors(self)
  598. for name in list(self.postprocessors.keys()):
  599. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  600. if name.partition('_')[0] == 'Paste':
  601. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  602. continue
  603. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  604. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  605. if name == 'hpgl':
  606. continue
  607. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  608. # ############################
  609. # ### LOAD LANGUAGES ####
  610. # ############################
  611. self.languages = fcTranslate.load_languages()
  612. for name in sorted(self.languages.values()):
  613. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  614. self.defaults = LoudDict()
  615. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  616. self.defaults.update({
  617. # Global APP Preferences
  618. "first_run": True,
  619. "units": "IN",
  620. "global_serial": 0,
  621. "global_stats": {},
  622. "global_tabs_detachable": True,
  623. "global_app_level": 'b',
  624. "global_portable": False,
  625. "global_language": 'English',
  626. "global_version_check": True,
  627. "global_send_stats": True,
  628. "global_pan_button": '2',
  629. "global_mselect_key": 'Control',
  630. "global_project_at_startup": False,
  631. "global_project_autohide": True,
  632. "global_toggle_tooltips": True,
  633. "global_worker_number": 2,
  634. "global_tolerance": 0.01,
  635. "global_open_style": True,
  636. "global_delete_confirmation": True,
  637. "global_compression_level": 3,
  638. "global_save_compressed": True,
  639. # Global GUI Preferences
  640. "global_gridx": 0.0393701,
  641. "global_gridy": 0.0393701,
  642. "global_snap_max": 0.001968504,
  643. "global_workspace": False,
  644. "global_workspaceT": "A4P",
  645. "global_grid_context_menu": {
  646. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  647. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  648. },
  649. "global_plot_fill": '#BBF268BF',
  650. "global_plot_line": '#006E20BF',
  651. "global_sel_fill": '#a5a5ffbf',
  652. "global_sel_line": '#0000ffbf',
  653. "global_alt_sel_fill": '#BBF268BF',
  654. "global_alt_sel_line": '#006E20BF',
  655. "global_draw_color": '#FF0000',
  656. "global_sel_draw_color": '#0000FF',
  657. "global_proj_item_color": '#000000',
  658. "global_proj_item_dis_color": '#b7b7cb',
  659. "global_toolbar_view": 511,
  660. "global_background_timeout": 300000, # Default value is 5 minutes
  661. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  662. # (python trace only for unknown errors),
  663. # 1 = show trace(show trace always),
  664. # 2 = (For the future).
  665. # Persistence
  666. "global_last_folder": None,
  667. "global_last_save_folder": None,
  668. # Default window geometry
  669. "global_def_win_x": 100,
  670. "global_def_win_y": 100,
  671. "global_def_win_w": 1024,
  672. "global_def_win_h": 650,
  673. "global_def_notebook_width": 1,
  674. # Constants...
  675. "global_defaults_save_period_ms": 20000, # Time between default saves.
  676. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  677. "global_shell_at_startup": False, # Show the shell at startup.
  678. "global_recent_limit": 10, # Max. items in recent list.
  679. "fit_key": 'V',
  680. "zoom_out_key": '-',
  681. "zoom_in_key": '=',
  682. "grid_toggle_key": 'G',
  683. "global_zoom_ratio": 1.5,
  684. "global_point_clipboard_format": "(%.4f, %.4f)",
  685. "global_zdownrate": None,
  686. # General GUI Settings
  687. "global_hover": False,
  688. "global_selection_shape": True,
  689. "global_layout": "compact",
  690. # Gerber General
  691. "gerber_plot": True,
  692. "gerber_solid": True,
  693. "gerber_multicolored": False,
  694. "gerber_isotooldia": 0.00787402,
  695. "gerber_isopasses": 1,
  696. "gerber_isooverlap": 0.00393701,
  697. # Gerber Options
  698. "gerber_combine_passes": False,
  699. "gerber_milling_type": "cl",
  700. "gerber_noncoppermargin": 0.00393701,
  701. "gerber_noncopperrounded": False,
  702. "gerber_bboxmargin": 0.00393701,
  703. "gerber_bboxrounded": False,
  704. "gerber_circle_steps": 128,
  705. "gerber_use_buffer_for_union": True,
  706. # Gerber Advanced Options
  707. "gerber_aperture_display": False,
  708. "gerber_aperture_scale_factor": 1.0,
  709. "gerber_aperture_buffer_factor": 0.0,
  710. "gerber_follow": False,
  711. # Gerber Export
  712. "gerber_exp_units": 'IN',
  713. "gerber_exp_integer": 2,
  714. "gerber_exp_decimals": 4,
  715. "gerber_exp_zeros": 'L',
  716. # Gerber Editor
  717. "gerber_editor_sel_limit": 30,
  718. "gerber_editor_newcode": 10,
  719. "gerber_editor_newsize": 0.8,
  720. "gerber_editor_newtype": 'C',
  721. "gerber_editor_newdim": "0.5, 0.5",
  722. "gerber_editor_array_size": 5,
  723. "gerber_editor_lin_axis": 'X',
  724. "gerber_editor_lin_pitch": 1,
  725. "gerber_editor_lin_angle": 0.0,
  726. "gerber_editor_circ_dir": 'CW',
  727. "gerber_editor_circ_angle": 0.0,
  728. "gerber_editor_scale_f": 1.0,
  729. "gerber_editor_buff_f": 0.1,
  730. "gerber_editor_ma_low": 0.0,
  731. "gerber_editor_ma_high": 1.0,
  732. # Excellon General
  733. "excellon_plot": True,
  734. "excellon_solid": True,
  735. "excellon_format_upper_in": 2,
  736. "excellon_format_lower_in": 4,
  737. "excellon_format_upper_mm": 3,
  738. "excellon_format_lower_mm": 3,
  739. "excellon_zeros": "L",
  740. "excellon_units": "INCH",
  741. "excellon_optimization_type": 'B',
  742. "excellon_search_time": 3,
  743. # Excellon Options
  744. "excellon_drillz": -0.0590551,
  745. "excellon_travelz": 0.0787402,
  746. "excellon_feedrate": 3.14961,
  747. "excellon_spindlespeed": None,
  748. "excellon_spindledir": 'CW',
  749. "excellon_dwell": False,
  750. "excellon_dwelltime": 1,
  751. "excellon_toolchange": False,
  752. "excellon_toolchangez": 0.5,
  753. "excellon_ppname_e": 'default',
  754. "excellon_tooldia": 0.0314961,
  755. "excellon_slot_tooldia": 0.0708661,
  756. "excellon_gcode_type": "drills",
  757. # Excellon Advanced Options
  758. "excellon_offset": 0.0,
  759. "excellon_toolchangexy": "0.0, 0.0",
  760. "excellon_startz": None,
  761. "excellon_endz": 0.5,
  762. "excellon_feedrate_rapid": 31.4961,
  763. "excellon_z_pdepth": -0.02,
  764. "excellon_feedrate_probe": 3.14961,
  765. "excellon_f_plunge": False,
  766. "excellon_f_retract": False,
  767. # Excellon Export
  768. "excellon_exp_units": 'INCH',
  769. "excellon_exp_format": 'ndec',
  770. "excellon_exp_integer": 2,
  771. "excellon_exp_decimals": 4,
  772. "excellon_exp_zeros": 'LZ',
  773. "excellon_exp_slot_type": 'routing',
  774. # Excellon Editor
  775. "excellon_editor_sel_limit": 30,
  776. "excellon_editor_newdia": 0.039,
  777. "excellon_editor_array_size": 5,
  778. "excellon_editor_lin_dir": 'X',
  779. "excellon_editor_lin_pitch": 0.1,
  780. "excellon_editor_lin_angle": 0.0,
  781. "excellon_editor_circ_dir": 'CW',
  782. "excellon_editor_circ_angle": 12,
  783. # Excellon Slots
  784. "excellon_editor_slot_direction": 'X',
  785. "excellon_editor_slot_angle": 0.0,
  786. "excellon_editor_slot_length": 5.0,
  787. # Excellon Slot Array
  788. "excellon_editor_slot_array_size": 5,
  789. "excellon_editor_slot_lin_dir": 'X',
  790. "excellon_editor_slot_lin_pitch": 0.1,
  791. "excellon_editor_slot_lin_angle": 0.0,
  792. "excellon_editor_slot_circ_dir": 'CW',
  793. "excellon_editor_slot_circ_angle": 0.0,
  794. # Geometry General
  795. "geometry_plot": True,
  796. "geometry_circle_steps": 128,
  797. "geometry_cnctooldia": "0.0944882",
  798. # Geometry Options
  799. "geometry_cutz": -0.0944882,
  800. "geometry_vtipdia": 0.1,
  801. "geometry_vtipangle": 30,
  802. "geometry_multidepth": False,
  803. "geometry_depthperpass": 0.0314961,
  804. "geometry_travelz": 0.0787402,
  805. "geometry_toolchange": False,
  806. "geometry_toolchangez": 0.5,
  807. "geometry_feedrate": 3.14961,
  808. "geometry_feedrate_z": 3.14961,
  809. "geometry_spindlespeed": None,
  810. "geometry_spindledir": 'CW',
  811. "geometry_dwell": False,
  812. "geometry_dwelltime": 1,
  813. "geometry_ppname_g": 'default',
  814. # Geometry Advanced Options
  815. "geometry_toolchangexy": "0.0, 0.0",
  816. "geometry_startz": None,
  817. "geometry_endz": 0.5,
  818. "geometry_feedrate_rapid": 3.14961,
  819. "geometry_extracut": False,
  820. "geometry_z_pdepth": -0.02,
  821. "geometry_f_plunge": False,
  822. "geometry_feedrate_probe": 3.14961,
  823. "geometry_segx": 0.0,
  824. "geometry_segy": 0.0,
  825. # Geometry Editor
  826. "geometry_editor_sel_limit": 30,
  827. # CNC Job General
  828. "cncjob_plot": True,
  829. "cncjob_plot_kind": 'all',
  830. "cncjob_annotation": True,
  831. "cncjob_annotation_fontsize": 9,
  832. "cncjob_annotation_fontcolor": '#990000',
  833. "cncjob_tooldia": 0.0393701,
  834. "cncjob_coords_type": "G90",
  835. "cncjob_coords_decimals": 4,
  836. "cncjob_fr_decimals": 2,
  837. "cncjob_steps_per_circle": 128,
  838. # CNC Job Options
  839. "cncjob_prepend": "",
  840. "cncjob_append": "",
  841. # CNC Job Advanced Options
  842. "cncjob_toolchange_macro": "",
  843. "cncjob_toolchange_macro_enable": False,
  844. "tools_ncctools": "0.0393701, 0.019685",
  845. "tools_nccorder": 'rev',
  846. "tools_nccoverlap": 0.015748,
  847. "tools_nccmargin": 0.0393701,
  848. "tools_nccmethod": "seed",
  849. "tools_nccconnect": True,
  850. "tools_ncccontour": True,
  851. "tools_nccrest": False,
  852. "tools_ncc_offset_choice": False,
  853. "tools_ncc_offset_value": 0.0000,
  854. "tools_nccref": 'itself',
  855. "tools_nccmilling_type": 'cl',
  856. "tools_ncctool_type": 'V',
  857. "tools_ncccutz": -0.001968504,
  858. "tools_ncctipdia": 0.00393701,
  859. "tools_ncctipangle": 30,
  860. "tools_cutouttooldia": 0.0944882,
  861. "tools_cutoutkind": "single",
  862. "tools_cutoutmargin": 0.00393701,
  863. "tools_cutoutgapsize": 0.15748,
  864. "tools_gaps_ff": "4",
  865. "tools_cutout_convexshape": False,
  866. "tools_painttooldia": 0.023622,
  867. "tools_paintorder": 'rev',
  868. "tools_paintoverlap": 0.015748,
  869. "tools_paintmargin": 0.0,
  870. "tools_paintmethod": "seed",
  871. "tools_selectmethod": "single",
  872. "tools_pathconnect": True,
  873. "tools_paintcontour": True,
  874. "tools_2sided_mirror_axis": "X",
  875. "tools_2sided_axis_loc": "point",
  876. "tools_2sided_drilldia": 0.0393701,
  877. "tools_film_type": 'neg',
  878. "tools_film_boundary": 0.0393701,
  879. "tools_film_scale": 0,
  880. "tools_panelize_spacing_columns": 0,
  881. "tools_panelize_spacing_rows": 0,
  882. "tools_panelize_columns": 1,
  883. "tools_panelize_rows": 1,
  884. "tools_panelize_constrain": False,
  885. "tools_panelize_constrainx": 0.0,
  886. "tools_panelize_constrainy": 0.0,
  887. "tools_panelize_panel_type": 'gerber',
  888. "tools_calc_vshape_tip_dia": 0.007874,
  889. "tools_calc_vshape_tip_angle": 30,
  890. "tools_calc_vshape_cut_z": 0.000787,
  891. "tools_calc_electro_length": 10.0,
  892. "tools_calc_electro_width": 10.0,
  893. "tools_calc_electro_cdensity": 13.0,
  894. "tools_calc_electro_growth": 10.0,
  895. "tools_transform_rotate": 90,
  896. "tools_transform_skew_x": 0.0,
  897. "tools_transform_skew_y": 0.0,
  898. "tools_transform_scale_x": 1.0,
  899. "tools_transform_scale_y": 1.0,
  900. "tools_transform_scale_link": True,
  901. "tools_transform_scale_reference": True,
  902. "tools_transform_offset_x": 0.0,
  903. "tools_transform_offset_y": 0.0,
  904. "tools_transform_mirror_reference": False,
  905. "tools_transform_mirror_point": (0, 0),
  906. "tools_solderpaste_tools": "0.0393701, 0.011811",
  907. "tools_solderpaste_new": 0.011811,
  908. "tools_solderpaste_z_start": 0.00019685039,
  909. "tools_solderpaste_z_dispense": 0.00393701,
  910. "tools_solderpaste_z_stop": 0.00019685039,
  911. "tools_solderpaste_z_travel": 0.00393701,
  912. "tools_solderpaste_z_toolchange": 0.0393701,
  913. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  914. "tools_solderpaste_frxy": 3.0,
  915. "tools_solderpaste_frz": 3.0,
  916. "tools_solderpaste_frz_dispense": 0.0393701,
  917. "tools_solderpaste_speedfwd": 20,
  918. "tools_solderpaste_dwellfwd": 1,
  919. "tools_solderpaste_speedrev": 10,
  920. "tools_solderpaste_dwellrev": 1,
  921. "tools_solderpaste_pp": 'Paste_1',
  922. "tools_sub_close_paths": True,
  923. # file associations
  924. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  925. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  926. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  927. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  928. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  929. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  930. })
  931. # ############################################################
  932. # ############### Load defaults from file ####################
  933. # ############################################################
  934. if user_defaults:
  935. self.load_defaults(filename='current_defaults')
  936. # #############################################################
  937. # ############## APPLY APP LANGUAGE ###########################
  938. # #############################################################
  939. ret_val = fcTranslate.apply_language('strings')
  940. if ret_val == "no language":
  941. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  942. log.debug("Could not find the Language files. The App strings are missing.")
  943. else:
  944. # make the current language the current selection on the language combobox
  945. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  946. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  947. # ##############################################################
  948. # ################# CREATE UNIQUE SERIAL NUMBER ################
  949. # ##############################################################
  950. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  951. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  952. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  953. self.save_defaults(silent=True)
  954. self.propagate_defaults(silent=True)
  955. self.restore_main_win_geom()
  956. def auto_save_defaults():
  957. try:
  958. self.save_defaults(silent=True)
  959. self.propagate_defaults(silent=True)
  960. finally:
  961. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  962. # the following lines activates automatic defaults save
  963. # if user_defaults:
  964. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  965. # self.options_form = PreferencesUI()
  966. self.options_form_fields = {
  967. "units": self.ui.general_options_form.general_app_group.units_radio,
  968. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  969. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  970. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  971. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  972. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  973. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  974. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  975. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  976. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  977. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  978. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  979. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  980. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  981. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  982. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  983. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  984. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  985. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  986. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  987. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  988. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  989. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  990. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  991. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  992. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  993. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  994. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  995. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  996. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  997. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  998. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  999. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1000. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1001. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1002. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1003. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1004. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1005. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1006. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  1007. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1008. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1009. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1010. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1011. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1012. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1013. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1014. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  1015. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1016. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1017. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1018. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1019. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1020. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1021. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1022. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1023. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1024. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1025. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1026. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1027. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1028. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  1029. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1030. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1031. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1032. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1033. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1034. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1035. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1036. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1037. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1038. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1039. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1040. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1041. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1042. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1043. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1044. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1045. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1046. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1047. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1048. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1049. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1050. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1051. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1052. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1053. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1054. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1055. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1056. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1057. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1058. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1059. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1060. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1061. }
  1062. for name in list(self.postprocessors.keys()):
  1063. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1064. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1065. self.options = LoudDict()
  1066. self.options.set_change_callback(self.on_options_dict_change)
  1067. self.options.update({
  1068. "units": "IN",
  1069. "global_gridx": 1.0,
  1070. "global_gridy": 1.0,
  1071. "global_snap_max": 0.05,
  1072. "global_background_timeout": 300000, # Default value is 5 minutes
  1073. "global_verbose_error_level": 0, # Shell verbosity:
  1074. # 0 = default(python trace only for unknown errors),
  1075. # 1 = show trace(show trace allways), 2 = (For the future).
  1076. "gerber_plot": True,
  1077. "gerber_solid": True,
  1078. "gerber_multicolored": False,
  1079. "gerber_isotooldia": 0.016,
  1080. "gerber_isopasses": 1,
  1081. "gerber_isooverlap": 0.15,
  1082. "gerber_combine_passes": True,
  1083. "gerber_noncoppermargin": 0.0,
  1084. "gerber_noncopperrounded": False,
  1085. "gerber_bboxmargin": 0.0,
  1086. "gerber_bboxrounded": False,
  1087. "excellon_plot": True,
  1088. "excellon_solid": False,
  1089. "excellon_format_upper_in": 2,
  1090. "excellon_format_lower_in": 4,
  1091. "excellon_format_upper_mm": 3,
  1092. "excellon_format_lower_mm": 3,
  1093. "excellon_units": 'INCH',
  1094. "excellon_optimization_type": 'B',
  1095. "excellon_search_time": 3,
  1096. "excellon_zeros": "L",
  1097. "excellon_drillz": -0.1,
  1098. "excellon_travelz": 0.1,
  1099. "excellon_feedrate": 3.0,
  1100. "excellon_feedrate_rapid": 3.0,
  1101. "excellon_spindlespeed": None,
  1102. "excellon_spindledir": 'CW',
  1103. "excellon_dwell": True,
  1104. "excellon_dwelltime": 1000,
  1105. "excellon_toolchange": False,
  1106. "excellon_toolchangez": 1.0,
  1107. "excellon_toolchangexy": "0.0, 0.0",
  1108. "excellon_tooldia": 0.016,
  1109. "excellon_ppname_e": 'default',
  1110. "excellon_f_plunge": False,
  1111. "excellon_startz": None,
  1112. "excellon_endz": 2.0,
  1113. "geometry_plot": True,
  1114. "geometry_segx": 0.0,
  1115. "geometry_segy": 0.0,
  1116. "geometry_cutz": -0.002,
  1117. "geometry_vtipdia": 0.1,
  1118. "geometry_vtipangle": 30,
  1119. "geometry_travelz": 0.1,
  1120. "geometry_feedrate": 3.0,
  1121. "geometry_feedrate_z": 3.0,
  1122. "geometry_feedrate_rapid": 3.0,
  1123. "geometry_spindlespeed": None,
  1124. "geometry_spindledir": 'CW',
  1125. "geometry_dwell": True,
  1126. "geometry_dwelltime": 1000,
  1127. "geometry_cnctooldia": 0.016,
  1128. "geometry_toolchange": False,
  1129. "geometry_toolchangez": 2.0,
  1130. "geometry_toolchangexy": "0.0, 0.0",
  1131. "geometry_startz": None,
  1132. "geometry_endz": 2.0,
  1133. "geometry_ppname_g": "default",
  1134. "geometry_f_plunge": False,
  1135. "geometry_depthperpass": 0.002,
  1136. "geometry_multidepth": False,
  1137. "geometry_extracut": False,
  1138. "cncjob_plot": True,
  1139. "cncjob_tooldia": 0.016,
  1140. "cncjob_prepend": "",
  1141. "cncjob_append": "",
  1142. "tools_ncctools": "1.0, 0.5",
  1143. "tools_nccoverlap": 0.4,
  1144. "tools_nccmargin": 1,
  1145. "tools_cutouttooldia": 0.07,
  1146. "tools_cutoutmargin": 0.1,
  1147. "tools_cutoutgapsize": 0.15,
  1148. "tools_gaps_ff": "8",
  1149. "tools_painttooldia": 0.07,
  1150. "tools_paintoverlap": 0.15,
  1151. "tools_paintmargin": 0.0,
  1152. "tools_paintmethod": "seed",
  1153. "tools_selectmethod": "single",
  1154. "tools_pathconnect": True,
  1155. "tools_paintcontour": True,
  1156. "tools_2sided_mirror_axis": "X",
  1157. "tools_2sided_axis_loc": 'point',
  1158. "tools_2sided_drilldia": 1,
  1159. "tools_film_type": 'neg',
  1160. "tools_film_boundary": 1,
  1161. "tools_film_scale": 0,
  1162. "tools_panelize_spacing_columns": 0,
  1163. "tools_panelize_spacing_rows": 0,
  1164. "tools_panelize_columns": 1,
  1165. "tools_panelize_rows": 1,
  1166. "tools_panelize_constrain": False,
  1167. "tools_panelize_constrainx": 0.0,
  1168. "tools_panelize_constrainy": 0.0
  1169. })
  1170. self.options.update(self.defaults) # Copy app defaults to project options
  1171. self.gen_form = None
  1172. self.ger_form = None
  1173. self.exc_form = None
  1174. self.geo_form = None
  1175. self.cnc_form = None
  1176. self.tools_form = None
  1177. self.fa_form = None
  1178. self.on_options_combo_change(0) # Will show the initial form
  1179. # ################################
  1180. # ### Initialize the color box's color in Preferences -> Global -> Color
  1181. # Init Plot Colors
  1182. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1183. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1184. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1185. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1186. int(self.defaults['global_plot_fill'][7:9], 16))
  1187. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1188. int(self.defaults['global_plot_fill'][7:9], 16))
  1189. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1190. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1191. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1192. # Init Left-Right Selection colors
  1193. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1194. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1195. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1196. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1197. int(self.defaults['global_sel_fill'][7:9], 16))
  1198. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1199. int(self.defaults['global_sel_fill'][7:9], 16))
  1200. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1201. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1202. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1203. # Init Right-Left Selection colors
  1204. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1205. self.defaults['global_alt_sel_fill'])
  1206. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1207. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1208. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1209. int(self.defaults['global_sel_fill'][7:9], 16))
  1210. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1211. int(self.defaults['global_sel_fill'][7:9], 16))
  1212. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1213. self.defaults['global_alt_sel_line'])
  1214. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1215. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1216. # Init Draw color and Selection Draw Color
  1217. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1218. self.defaults['global_draw_color'])
  1219. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1220. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1221. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1222. self.defaults['global_sel_draw_color'])
  1223. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1224. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1225. # Init Project Items color
  1226. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1227. self.defaults['global_proj_item_color'])
  1228. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1229. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1230. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1231. self.defaults['global_proj_item_dis_color'])
  1232. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1233. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1234. # Init the Annotation CNC Job color
  1235. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1236. self.defaults['cncjob_annotation_fontcolor'])
  1237. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1238. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1239. # ### End of Data ####
  1240. # ###############################################
  1241. # ############# SETUP Plot Area #################
  1242. # ###############################################
  1243. start_plot_time = time.time() # debug
  1244. self.plotcanvas = None
  1245. self.app_cursor = None
  1246. self.hover_shapes = None
  1247. self.on_plotcanvas_setup()
  1248. end_plot_time = time.time()
  1249. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1250. self.ui.splitter.setStretchFactor(1, 2)
  1251. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1252. # depending on from where those tools are called different actions can be done
  1253. self.call_source = 'app'
  1254. # ##############################################
  1255. # ######### SETUP OBJECT COLLECTION ############
  1256. # ##############################################
  1257. self.collection = ObjectCollection(self)
  1258. self.ui.project_tab_layout.addWidget(self.collection.view)
  1259. # ### Adjust tabs width ## ##
  1260. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1261. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1262. self.collection.view.setMinimumWidth(290)
  1263. self.log.debug("Finished creating Object Collection.")
  1264. # ###############################################
  1265. # ############# Worker SETUP ####################
  1266. # ###############################################
  1267. if self.defaults["global_worker_number"]:
  1268. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1269. else:
  1270. self.workers = WorkerStack(workers_number=2)
  1271. self.worker_task.connect(self.workers.add_task)
  1272. self.log.debug("Finished creating Workers crew.")
  1273. # ################################################
  1274. # ############### Signal handling ################
  1275. # ################################################
  1276. # ############# Custom signals ##################
  1277. # signal for displaying messages in status bar
  1278. self.inform.connect(self.info)
  1279. # signal to be called when the app is quiting
  1280. self.app_quit.connect(self.quit_application)
  1281. self.message.connect(self.message_dialog)
  1282. self.progress.connect(self.set_progress_bar)
  1283. # signals that are emitted when object state changes
  1284. self.object_created.connect(self.on_object_created)
  1285. self.object_changed.connect(self.on_object_changed)
  1286. self.object_plotted.connect(self.on_object_plotted)
  1287. self.plots_updated.connect(self.on_plots_updated)
  1288. # signals emitted when file state change
  1289. self.file_opened.connect(self.register_recent)
  1290. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1291. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1292. # ############# Standard signals ###################
  1293. # ### Menu
  1294. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1295. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1296. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1297. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1298. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1299. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1300. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1301. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1302. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1303. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1304. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1305. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1306. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1307. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1308. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1309. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1310. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1311. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1312. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1313. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1314. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1315. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1316. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1317. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1318. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1319. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1320. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1321. self.ui.menufile_exit.triggered.connect(self.final_save)
  1322. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1323. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1324. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1325. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1326. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1327. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1328. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1329. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1330. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1331. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1332. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1333. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1334. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1335. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1336. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1337. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1338. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1339. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1340. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1341. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1342. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1343. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1344. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1345. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1346. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1347. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1348. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1349. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1350. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1351. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1352. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1353. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1354. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1355. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1356. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1357. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1358. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1359. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1360. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1361. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1362. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1363. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1364. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1365. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1366. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1367. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1368. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1369. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1370. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1371. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1372. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1373. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1374. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1375. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1376. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1377. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1378. # ToolBar signals
  1379. self.connect_toolbar_signals()
  1380. # Notebook signals
  1381. # make the right click on the notebook tab connect to a function
  1382. self.ui.notebook.setupContextMenu()
  1383. self.ui.notebook.addContextMenu(
  1384. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1385. initial_checked=self.defaults["global_tabs_detachable"])
  1386. # activate initial state
  1387. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1388. # Context Menu
  1389. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1390. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1391. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1392. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1393. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1394. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1395. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1396. self.ui.clearplot.triggered.connect(self.clear_plots)
  1397. self.ui.replot.triggered.connect(self.plot_all)
  1398. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1399. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1400. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1401. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1402. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1403. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1404. # Preferences Plot Area TAB
  1405. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1406. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1407. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1408. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1409. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1410. # ##############################
  1411. # ### GUI PREFERENCES SIGNALS ##
  1412. # ##############################
  1413. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1414. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1415. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1416. )
  1417. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1418. lambda: self.on_toggle_units(no_pref=False))
  1419. # ###############################################################
  1420. # ################### GUI COLORS SIGNALS ########################
  1421. # ###############################################################
  1422. # Setting plot colors signals
  1423. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1424. self.on_pf_color_entry)
  1425. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1426. self.on_pf_color_button)
  1427. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1428. self.on_pf_color_spinner)
  1429. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1430. self.on_pf_color_slider)
  1431. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1432. self.on_pl_color_entry)
  1433. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1434. self.on_pl_color_button)
  1435. # Setting selection (left - right) colors signals
  1436. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1437. self.on_sf_color_entry)
  1438. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1439. self.on_sf_color_button)
  1440. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1441. self.on_sf_color_spinner)
  1442. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1443. self.on_sf_color_slider)
  1444. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1445. self.on_sl_color_entry)
  1446. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1447. self.on_sl_color_button)
  1448. # Setting selection (right - left) colors signals
  1449. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1450. self.on_alt_sf_color_entry)
  1451. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1452. self.on_alt_sf_color_button)
  1453. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1454. self.on_alt_sf_color_spinner)
  1455. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1456. self.on_alt_sf_color_slider)
  1457. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1458. self.on_alt_sl_color_entry)
  1459. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1460. self.on_alt_sl_color_button)
  1461. # Setting Editor Draw colors signals
  1462. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1463. self.on_draw_color_entry)
  1464. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1465. self.on_draw_color_button)
  1466. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1467. self.on_sel_draw_color_entry)
  1468. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1469. self.on_sel_draw_color_button)
  1470. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1471. self.on_proj_color_entry)
  1472. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1473. self.on_proj_color_button)
  1474. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1475. self.on_proj_color_dis_entry)
  1476. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1477. self.on_proj_color_dis_button)
  1478. # ########## workspace setting signals ###########
  1479. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1480. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1481. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1482. # ########## CNC Job related signals #############
  1483. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1484. self.on_cnc_custom_parameters)
  1485. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1486. self.on_annotation_fontcolor_entry)
  1487. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1488. self.on_annotation_fontcolor_button)
  1489. # ########## Modify G-CODE Plot Area TAB ###########
  1490. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1491. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1492. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1493. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1494. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1495. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1496. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1497. # portability changed signal
  1498. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1499. # Object list
  1500. self.collection.view.activated.connect(self.on_row_activated)
  1501. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1502. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1503. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1504. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1505. self.on_excellon_defaults_button)
  1506. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1507. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1508. self.on_excellon_options_button)
  1509. # when there are arguments at application startup this get launched
  1510. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1511. # connect the 'Apply' buttons from the Preferences/File Associations
  1512. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1513. lambda: self.on_register_files(obj_type='excellon'))
  1514. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1515. lambda: self.on_register_files(obj_type='gcode'))
  1516. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1517. lambda: self.on_register_files(obj_type='gerber'))
  1518. # connect the abort_all_tasks related slots to the related signals
  1519. self.proc_container.idle_flag.connect(self.app_is_idle)
  1520. # #####################################################################################
  1521. # ########### FINISHED CONNECTING SIGNALS #############################################
  1522. # #####################################################################################
  1523. self.log.debug("Finished connecting Signals.")
  1524. # #####################################################################################
  1525. # ########################## Other setups #############################################
  1526. # #####################################################################################
  1527. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1528. self.tool_tab_locked = False
  1529. # decide if to show or hide the Notebook side of the screen at startup
  1530. if self.defaults["global_project_at_startup"] is True:
  1531. self.ui.splitter.setSizes([1, 1])
  1532. else:
  1533. self.ui.splitter.setSizes([0, 1])
  1534. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1535. self.setup_obj_classes()
  1536. self.setup_recent_items()
  1537. self.setup_component_editor()
  1538. # #####################################################################################
  1539. # ######################### Auto-complete KEYWORDS ####################################
  1540. # #####################################################################################
  1541. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1542. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1543. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1544. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1545. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1546. 'join_geometry', 'list_sys', 'listsys', 'mill', 'millholes', 'mirror', 'ncc',
  1547. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1548. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1549. 'pan', 'panel', 'panelize', 'plot', 'save', 'save_project', 'save_sys', 'scale',
  1550. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1551. 'version', 'write_gcode'
  1552. ]
  1553. self.ordinary_keywords = ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1554. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'dist', 'drillz',
  1555. 'endz', 'extracut', 'factor', 'False', 'false', 'feedrate', 'feedrate_rapid',
  1556. 'filename', 'follow', 'gaps', 'gapsize', 'grid', 'gridoffset', 'gridoffsetx',
  1557. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1558. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1559. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1560. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1561. 'toolchange', 'toolchangez', 'tooldia', 'tools', 'travelz', 'True', 'true', 'type',
  1562. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1563. ]
  1564. self.tcl_keywords = [
  1565. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1566. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1567. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1568. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1569. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1570. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1571. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1572. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1573. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1574. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1575. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1576. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1577. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1578. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1579. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1580. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1581. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1582. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1583. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1584. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1585. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1586. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1587. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1588. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1589. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1590. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1591. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1592. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1593. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1594. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1595. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1596. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1597. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1598. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1599. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1600. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1601. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1602. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1603. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1604. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1605. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1606. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1607. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1608. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1609. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1610. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1611. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1612. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1613. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1614. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1615. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1616. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1617. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1618. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1619. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1620. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1621. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1622. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1623. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1624. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1625. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1626. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1627. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1628. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1629. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1630. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1631. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1632. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1633. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1634. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1635. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1636. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1637. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1638. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1639. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1640. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1641. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1642. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1643. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1644. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1645. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1646. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1647. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1648. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1649. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1650. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1651. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1652. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1653. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1654. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1655. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1656. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1657. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1658. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1659. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1660. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1661. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1662. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1663. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1664. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1665. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1666. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1667. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1668. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1669. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1670. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1671. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1672. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1673. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1674. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1675. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1676. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1677. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1678. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1679. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1680. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1681. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1682. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1683. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1684. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1685. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1686. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1687. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1688. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1689. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1690. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1691. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1692. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1693. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1694. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1695. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1696. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1697. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1698. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1699. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1700. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1701. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1702. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1703. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1704. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1705. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1706. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1707. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1708. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1709. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1710. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1711. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1712. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1713. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1714. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1715. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1716. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1717. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1718. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1719. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1720. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1721. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1722. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1723. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1724. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1725. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1726. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1727. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1728. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1729. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1730. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1731. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1732. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1733. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1734. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1735. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1736. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1737. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1738. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1739. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1740. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1741. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1742. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1743. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1744. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1745. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1746. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1747. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1748. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1749. ]
  1750. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1751. # ####################################################################################
  1752. # ####################### Shell SETUP ################################################
  1753. # ####################################################################################
  1754. self.shell = FCShell(self, version=self.version)
  1755. self.shell._edit.set_model_data(self.myKeywords)
  1756. self.ui.code_editor.set_model_data(self.myKeywords)
  1757. self.shell.setWindowIcon(self.ui.app_icon)
  1758. self.shell.setWindowTitle("FlatCAM Shell")
  1759. self.shell.resize(*self.defaults["global_shell_shape"])
  1760. self.shell.append_output("FlatCAM %s - " % self.version)
  1761. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1762. self.init_tcl()
  1763. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1764. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1765. self.ui.shell_dock.setWidget(self.shell)
  1766. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1767. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1768. QtWidgets.QDockWidget.DockWidgetFloatable |
  1769. QtWidgets.QDockWidget.DockWidgetClosable)
  1770. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1771. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1772. if self.defaults["global_shell_at_startup"]:
  1773. self.ui.shell_dock.show()
  1774. else:
  1775. self.ui.shell_dock.hide()
  1776. # ##################################################################################
  1777. # ###################### Tools and Plugins #########################################
  1778. # ##################################################################################
  1779. self.dblsidedtool = None
  1780. self.measurement_tool = None
  1781. self.panelize_tool = None
  1782. self.film_tool = None
  1783. self.paste_tool = None
  1784. self.calculator_tool = None
  1785. self.sub_tool = None
  1786. self.move_tool = None
  1787. self.cutout_tool = None
  1788. self.ncclear_tool = None
  1789. self.paint_tool = None
  1790. self.transform_tool = None
  1791. self.properties_tool = None
  1792. self.pdf_tool = None
  1793. self.image_tool = None
  1794. self.pcb_wizard_tool = None
  1795. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1796. self.install_tools()
  1797. # ### System Font Parsing ###
  1798. # self.f_parse = ParseFont(self)
  1799. # self.parse_system_fonts()
  1800. # #####################################################################################
  1801. # ########################## START-UP ARGUMENTS #######################################
  1802. # #####################################################################################
  1803. # test if the program was started with a script as parameter
  1804. if self.cmd_line_shellfile:
  1805. try:
  1806. with open(self.cmd_line_shellfile, "r") as myfile:
  1807. cmd_line_shellfile_text = myfile.read()
  1808. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1809. except Exception as ext:
  1810. print("ERROR: ", ext)
  1811. sys.exit(2)
  1812. # #####################################################################################
  1813. # ######################## Check for updates ##########################################
  1814. # #####################################################################################
  1815. # Separate thread (Not worker)
  1816. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1817. if (self.beta is False or self.beta is None) and \
  1818. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1819. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1820. self.thr2 = QtCore.QThread()
  1821. self.worker_task.emit({'fcn': self.version_check,
  1822. 'params': []})
  1823. self.thr2.start(QtCore.QThread.LowPriority)
  1824. # #####################################################################################
  1825. # ###################### Variables for global usage ###################################
  1826. # #####################################################################################
  1827. # register files with FlatCAM; it works only for Windows for now
  1828. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1829. self.on_register_files()
  1830. # coordinates for relative position display
  1831. self.rel_point1 = (0, 0)
  1832. self.rel_point2 = (0, 0)
  1833. # variable to store coordinates
  1834. self.pos = (0, 0)
  1835. self.pos_jump = (0, 0)
  1836. # variable to store mouse coordinates
  1837. self.mouse = [0, 0]
  1838. # decide if we have a double click or single click
  1839. self.doubleclick = False
  1840. # variable to store if a command is active (then the var is not None) and which one it is
  1841. self.command_active = None
  1842. # variable to store the status of moving selection action
  1843. # None value means that it's not an selection action
  1844. # True value = a selection from left to right
  1845. # False value = a selection from right to left
  1846. self.selection_type = None
  1847. # List to store the objects that are currently loaded in FlatCAM
  1848. # This list is updated on each object creation or object delete
  1849. self.all_objects_list = []
  1850. # List to store the objects that are selected
  1851. self.sel_objects_list = []
  1852. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1853. self.key_modifiers = None
  1854. # Variable to hold the status of the axis
  1855. self.toggle_axis = True
  1856. # Variable to store the status of the fullscreen event
  1857. self.toggle_fscreen = False
  1858. # Variable to store the status of the code editor
  1859. self.toggle_codeeditor = False
  1860. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1861. self.click_noproject = False
  1862. self.cursor = None
  1863. # Variable to store the GCODE that was edited
  1864. self.gcode_edited = ""
  1865. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1866. self.preferences_changed_flag = False
  1867. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1868. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1869. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1870. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1871. ]
  1872. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1873. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1874. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1875. 'mpf'
  1876. ]
  1877. self.svg_list = ['svg']
  1878. self.dxf_list = ['dxf']
  1879. self.pdf_list = ['pdf']
  1880. self.prj_list = ['flatprj']
  1881. self.conf_list = ['flatconfig']
  1882. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1883. # flag for polygons not cleared
  1884. self.poly_not_cleared = False
  1885. # VisPy visuals
  1886. self.isHovering = False
  1887. self.notHovering = True
  1888. # when True, the app has to return from any thread
  1889. self.abort_flag = False
  1890. # ###############################################################################
  1891. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1892. # ############# It's done only once after install ###############
  1893. # ###############################################################################
  1894. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1895. fac_def_from_file = factory_file.read()
  1896. factory_defaults = json.loads(fac_def_from_file)
  1897. # if the file contain an empty dictionary then save the factory defaults into the file
  1898. if not factory_defaults:
  1899. self.save_factory_defaults(silent=False)
  1900. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1901. initial_lay = 'compact'
  1902. self.on_layout(lay=initial_lay)
  1903. # Set the combobox in Preferences to the current layout
  1904. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1905. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1906. factory_file.close()
  1907. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1908. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1909. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1910. # after the first run, this object should be False
  1911. self.defaults["first_run"] = False
  1912. # ###############################################################################
  1913. # ################# ADDING FlatCAM EDITORS section ##############################
  1914. # ###############################################################################
  1915. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1916. # at the first launch of the App , the editors will not be functional.
  1917. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1918. self.exc_editor = FlatCAMExcEditor(self)
  1919. self.grb_editor = FlatCAMGrbEditor(self)
  1920. self.log.debug("Finished adding FlatCAM Editor's.")
  1921. self.set_ui_title(name=_("New Project - Not saved"))
  1922. # ###############################################################################
  1923. # ####################### Finished the CONSTRUCTOR ##############################
  1924. # ###############################################################################
  1925. App.log.debug("END of constructor. Releasing control.")
  1926. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1927. # the path/file_name must be enclosed in quotes if it contain spaces
  1928. if App.args:
  1929. self.args_at_startup.emit(App.args)
  1930. @staticmethod
  1931. def copy_and_overwrite(from_path, to_path):
  1932. """
  1933. From here:
  1934. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1935. :param from_path: source path
  1936. :param to_path: destination path
  1937. :return: None
  1938. """
  1939. if os.path.exists(to_path):
  1940. shutil.rmtree(to_path)
  1941. try:
  1942. shutil.copytree(from_path, to_path)
  1943. except FileNotFoundError:
  1944. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1945. shutil.copytree(from_new_path, to_path)
  1946. def on_startup_args(self, args=None):
  1947. """
  1948. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1949. :param args: a list containing the application args at startup
  1950. :return: None
  1951. """
  1952. if args:
  1953. args_to_process = args
  1954. else:
  1955. args_to_process = App.args
  1956. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1957. for argument in args_to_process:
  1958. if '.FlatPrj' in argument:
  1959. try:
  1960. project_name = str(argument)
  1961. if project_name == "":
  1962. self.inform.emit(_("Open cancelled."))
  1963. else:
  1964. # self.open_project(project_name)
  1965. run_from_arg = True
  1966. # self.worker_task.emit({'fcn': self.open_project,
  1967. # 'params': [project_name, run_from_arg]})
  1968. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1969. except Exception as e:
  1970. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1971. elif '.FlatConfig' in argument:
  1972. try:
  1973. file_name = str(argument)
  1974. if file_name == "":
  1975. self.inform.emit(_("Open Config file failed."))
  1976. else:
  1977. # run_from_arg = True
  1978. # self.worker_task.emit({'fcn': self.open_config_file,
  1979. # 'params': [file_name, run_from_arg]})
  1980. self.open_config_file(file_name, run_from_arg=True)
  1981. except Exception as e:
  1982. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1983. elif '.FlatScript' in argument:
  1984. try:
  1985. file_name = str(argument)
  1986. if file_name == "":
  1987. self.inform.emit(_("Open Script file failed."))
  1988. else:
  1989. # run_from_arg = True
  1990. # self.worker_task.emit({'fcn': self.open_script_file,
  1991. # 'params': [file_name, run_from_arg]})
  1992. self.on_filerunscript(name=file_name)
  1993. except Exception as e:
  1994. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1995. else:
  1996. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1997. proc_arg = argument.lower()
  1998. for ext in exc_list:
  1999. proc_ext = ext.replace(' ', '')
  2000. if proc_ext.lower() in proc_arg and proc_ext != '':
  2001. file_name = str(argument)
  2002. if file_name == "":
  2003. self.inform.emit(_("Open Excellon file failed."))
  2004. else:
  2005. self.on_fileopenexcellon(name=file_name)
  2006. return
  2007. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2008. for ext in gco_list:
  2009. proc_ext = ext.replace(' ', '')
  2010. if proc_ext.lower() in proc_arg and proc_ext != '':
  2011. file_name = str(argument)
  2012. if file_name == "":
  2013. self.inform.emit(_("Open GCode file failed."))
  2014. else:
  2015. self.on_fileopengcode(name=file_name)
  2016. return
  2017. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2018. for ext in grb_list:
  2019. proc_ext = ext.replace(' ', '')
  2020. if proc_ext.lower() in proc_arg and proc_ext != '':
  2021. file_name = str(argument)
  2022. if file_name == "":
  2023. self.inform.emit(_("Open Gerber file failed."))
  2024. else:
  2025. self.on_fileopengerber(name=file_name)
  2026. return
  2027. def set_ui_title(self, name):
  2028. """
  2029. Sets the title of the main window.
  2030. :param name: String that store the project path and project name
  2031. :return: None
  2032. """
  2033. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2034. (self.version,
  2035. ('BETA' if self.beta else ''),
  2036. platform.architecture()[0],
  2037. name)
  2038. )
  2039. def defaults_read_form(self):
  2040. """
  2041. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2042. :return: None
  2043. """
  2044. for option in self.defaults_form_fields:
  2045. try:
  2046. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2047. except Exception as e:
  2048. log.debug("App.defaults_read_form() --> %s" % str(e))
  2049. def defaults_write_form(self, factor=None, fl_units=None):
  2050. """
  2051. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2052. self.defaults dictionary.
  2053. :param factor: will apply a factor to the values that written in the GUI elements
  2054. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2055. :return: None
  2056. """
  2057. for option in self.defaults:
  2058. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2059. # try:
  2060. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2061. # except KeyError:
  2062. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2063. # # TODO: Rethink this?
  2064. # pass
  2065. def defaults_write_form_field(self, field, factor=None, units=None):
  2066. """
  2067. Basically it is the worker in the self.defaults_write_form()
  2068. :param field: the GUI element in Preferences GUI to be updated
  2069. :param factor: factor to be applied to the field parameter
  2070. :param units: current FLatCAM measuring units
  2071. :return: None, it updates GUI elements
  2072. """
  2073. try:
  2074. if factor is None:
  2075. if units is None:
  2076. self.defaults_form_fields[field].set_value(self.defaults[field])
  2077. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2078. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2079. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2080. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2081. else:
  2082. if units is None:
  2083. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2084. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2085. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2086. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2087. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2088. except KeyError:
  2089. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2090. # TODO: Rethink this?
  2091. pass
  2092. except AttributeError:
  2093. log.debug(field)
  2094. def clear_pool(self):
  2095. """
  2096. Clear the multiprocessing pool and calls garbage collector.
  2097. :return: None
  2098. """
  2099. self.pool.close()
  2100. self.pool = Pool()
  2101. self.pool_recreated.emit(self.pool)
  2102. gc.collect()
  2103. def install_tools(self):
  2104. """
  2105. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2106. Instantiation of the Tools classes.
  2107. The order that the tools are installed is important as they can depend on each other install position.
  2108. :return: None
  2109. """
  2110. self.dblsidedtool = DblSidedTool(self)
  2111. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2112. self.measurement_tool = Measurement(self)
  2113. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2114. self.panelize_tool = Panelize(self)
  2115. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2116. self.film_tool = Film(self)
  2117. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2118. self.paste_tool = SolderPaste(self)
  2119. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2120. self.calculator_tool = ToolCalculator(self)
  2121. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2122. self.sub_tool = ToolSub(self)
  2123. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2124. self.move_tool = ToolMove(self)
  2125. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2126. before=self.ui.menueditorigin)
  2127. self.cutout_tool = CutOut(self)
  2128. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2129. before=self.measurement_tool.menuAction)
  2130. self.ncclear_tool = NonCopperClear(self)
  2131. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2132. before=self.measurement_tool.menuAction, separator=True)
  2133. self.paint_tool = ToolPaint(self)
  2134. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2135. before=self.measurement_tool.menuAction, separator=True)
  2136. self.transform_tool = ToolTransform(self)
  2137. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2138. self.properties_tool = Properties(self)
  2139. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2140. self.pdf_tool = ToolPDF(self)
  2141. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2142. separator=True)
  2143. self.image_tool = ToolImage(self)
  2144. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2145. separator=True)
  2146. self.pcb_wizard_tool = PcbWizard(self)
  2147. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2148. self.log.debug("Tools are installed.")
  2149. def remove_tools(self):
  2150. """
  2151. Will remove all the actions in the Tool menu.
  2152. :return: None
  2153. """
  2154. for act in self.ui.menutool.actions():
  2155. self.ui.menutool.removeAction(act)
  2156. def init_tools(self):
  2157. """
  2158. Initialize the Tool tab in the notebook side of the central widget.
  2159. Remove the actions in the Tools menu.
  2160. Instantiate again the FlatCAM tools (plugins).
  2161. All this is required when changing the layout: standard, compact etc.
  2162. :return: None
  2163. """
  2164. log.debug("init_tools()")
  2165. # delete the data currently in the Tools Tab and the Tab itself
  2166. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2167. if widget is not None:
  2168. widget.deleteLater()
  2169. self.ui.notebook.removeTab(2)
  2170. # rebuild the Tools Tab
  2171. self.ui.tool_tab = QtWidgets.QWidget()
  2172. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2173. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2174. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2175. self.ui.tool_scroll_area = VerticalScrollArea()
  2176. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2177. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2178. # first remove all of them
  2179. self.remove_tools()
  2180. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2181. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2182. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2183. # third install all of them
  2184. self.install_tools()
  2185. self.log.debug("Tools are initialized.")
  2186. # def parse_system_fonts(self):
  2187. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2188. # 'params': []})
  2189. def connect_toolbar_signals(self):
  2190. """
  2191. Reconnect the signals to the actions in the toolbar.
  2192. This has to be done each time after the FlatCAM tools are removed/installed.
  2193. :return: None
  2194. """
  2195. # Toolbar
  2196. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2197. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2198. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2199. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2200. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2201. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2202. self.ui.replot_btn.triggered.connect(self.plot_all)
  2203. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2204. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2205. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2206. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2207. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2208. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2209. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2210. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2211. self.ui.delete_btn.triggered.connect(self.on_delete)
  2212. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2213. # Tools Toolbar Signals
  2214. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2215. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2216. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2217. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2218. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2219. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2220. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2221. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2222. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2223. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2224. def object2editor(self):
  2225. """
  2226. Send the current Geometry or Excellon object (if any) into the it's editor.
  2227. :return: None
  2228. """
  2229. self.report_usage("object2editor()")
  2230. edited_object = self.collection.get_active()
  2231. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2232. isinstance(edited_object, FlatCAMExcellon):
  2233. pass
  2234. else:
  2235. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  2236. return
  2237. if isinstance(edited_object, FlatCAMGeometry):
  2238. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2239. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2240. # we set the notebook to hidden
  2241. self.ui.splitter.setSizes([0, 1])
  2242. if edited_object.multigeo is True:
  2243. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2244. if len(edited_tools) > 1:
  2245. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2246. "is not possible.\n"
  2247. "Edit only one geometry at a time."))
  2248. # determine the tool dia of the selected tool
  2249. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2250. # now find the key in the edited_object.tools that has this tooldia
  2251. multi_tool = 1
  2252. for tool in edited_object.tools:
  2253. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2254. multi_tool = tool
  2255. break
  2256. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2257. else:
  2258. self.geo_editor.edit_fcgeometry(edited_object)
  2259. # set call source to the Editor we go into
  2260. self.call_source = 'geo_editor'
  2261. elif isinstance(edited_object, FlatCAMExcellon):
  2262. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2263. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2264. if self.ui.splitter.sizes()[0] == 0:
  2265. self.ui.splitter.setSizes([1, 1])
  2266. self.exc_editor.edit_fcexcellon(edited_object)
  2267. # set call source to the Editor we go into
  2268. self.call_source = 'exc_editor'
  2269. elif isinstance(edited_object, FlatCAMGerber):
  2270. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2271. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2272. if self.ui.splitter.sizes()[0] == 0:
  2273. self.ui.splitter.setSizes([1, 1])
  2274. self.grb_editor.edit_fcgerber(edited_object)
  2275. # set call source to the Editor we go into
  2276. self.call_source = 'grb_editor'
  2277. # make sure that we can't select another object while in Editor Mode:
  2278. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2279. self.ui.project_frame.setDisabled(True)
  2280. # delete any selection shape that might be active as they are not relevant in Editor
  2281. self.delete_selection_shape()
  2282. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2283. self.ui.plot_tab_area.protectTab(0)
  2284. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  2285. self.should_we_save = True
  2286. def editor2object(self, cleanup=None):
  2287. """
  2288. Transfers the Geometry or Excellon from it's editor to the current object.
  2289. :return: None
  2290. """
  2291. self.report_usage("editor2object()")
  2292. # do not update a geometry or excellon object unless it comes out of an editor
  2293. if self.call_source != 'app':
  2294. edited_obj = self.collection.get_active()
  2295. if cleanup is None:
  2296. msgbox = QtWidgets.QMessageBox()
  2297. msgbox.setText(_("Do you want to save the edited object?"))
  2298. msgbox.setWindowTitle(_("Close Editor"))
  2299. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2300. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2301. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2302. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2303. msgbox.setDefaultButton(bt_yes)
  2304. msgbox.exec_()
  2305. response = msgbox.clickedButton()
  2306. if response == bt_yes:
  2307. # clean the Tools Tab
  2308. self.ui.tool_scroll_area.takeWidget()
  2309. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2310. self.ui.notebook.setTabText(2, "Tool")
  2311. if isinstance(edited_obj, FlatCAMGeometry):
  2312. obj_type = "Geometry"
  2313. if cleanup is None:
  2314. self.geo_editor.update_fcgeometry(edited_obj)
  2315. self.geo_editor.update_options(edited_obj)
  2316. self.geo_editor.deactivate()
  2317. # update the geo object options so it is including the bounding box values
  2318. try:
  2319. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2320. edited_obj.options['xmin'] = xmin
  2321. edited_obj.options['ymin'] = ymin
  2322. edited_obj.options['xmax'] = xmax
  2323. edited_obj.options['ymax'] = ymax
  2324. except AttributeError as e:
  2325. self.inform.emit(_("[WARNING] Object empty after edit."))
  2326. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2327. elif isinstance(edited_obj, FlatCAMGerber):
  2328. obj_type = "Gerber"
  2329. if cleanup is None:
  2330. self.grb_editor.update_fcgerber()
  2331. self.grb_editor.update_options(edited_obj)
  2332. self.grb_editor.deactivate_grb_editor()
  2333. # delete the old object (the source object) if it was an empty one
  2334. if len(edited_obj.solid_geometry) == 0:
  2335. old_name = edited_obj.options['name']
  2336. self.collection.set_active(old_name)
  2337. self.collection.delete_active()
  2338. elif isinstance(edited_obj, FlatCAMExcellon):
  2339. obj_type = "Excellon"
  2340. if cleanup is None:
  2341. self.exc_editor.update_fcexcellon(edited_obj)
  2342. self.exc_editor.update_options(edited_obj)
  2343. self.exc_editor.deactivate()
  2344. else:
  2345. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2346. return
  2347. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  2348. elif response == bt_no:
  2349. # clean the Tools Tab
  2350. self.ui.tool_scroll_area.takeWidget()
  2351. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2352. self.ui.notebook.setTabText(2, "Tool")
  2353. if isinstance(edited_obj, FlatCAMGeometry):
  2354. self.geo_editor.deactivate()
  2355. elif isinstance(edited_obj, FlatCAMGerber):
  2356. self.grb_editor.deactivate_grb_editor()
  2357. elif isinstance(edited_obj, FlatCAMExcellon):
  2358. self.exc_editor.deactivate()
  2359. # set focus on the project tab
  2360. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2361. else:
  2362. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2363. return
  2364. elif response == bt_cancel:
  2365. return
  2366. else:
  2367. if isinstance(edited_obj, FlatCAMGeometry):
  2368. self.geo_editor.deactivate()
  2369. elif isinstance(edited_obj, FlatCAMGerber):
  2370. self.grb_editor.deactivate_grb_editor()
  2371. elif isinstance(edited_obj, FlatCAMExcellon):
  2372. self.exc_editor.deactivate()
  2373. else:
  2374. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2375. return
  2376. # if notebook is hidden we show it
  2377. if self.ui.splitter.sizes()[0] == 0:
  2378. self.ui.splitter.setSizes([1, 1])
  2379. # restore the call_source to app
  2380. self.call_source = 'app'
  2381. edited_obj.plot()
  2382. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2383. self.ui.plot_tab_area.protectTab(0)
  2384. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2385. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2386. self.ui.project_frame.setDisabled(False)
  2387. def get_last_folder(self):
  2388. """
  2389. Get the folder path from where the last file was opened.
  2390. :return: String, last opened folder path
  2391. """
  2392. return self.defaults["global_last_folder"]
  2393. def get_last_save_folder(self):
  2394. """
  2395. Get the folder path from where the last file was saved.
  2396. :return: String, last saved folder path
  2397. """
  2398. loc = self.defaults["global_last_save_folder"]
  2399. if loc is None:
  2400. loc = self.defaults["global_last_folder"]
  2401. if loc is None:
  2402. loc = os.path.dirname(__file__)
  2403. return loc
  2404. def report_usage(self, resource):
  2405. """
  2406. Increments usage counter for the given resource
  2407. in self.defaults['global_stats'].
  2408. :param resource: Name of the resource.
  2409. :return: None
  2410. """
  2411. if resource in self.defaults['global_stats']:
  2412. self.defaults['global_stats'][resource] += 1
  2413. else:
  2414. self.defaults['global_stats'][resource] = 1
  2415. def init_tcl(self):
  2416. """
  2417. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2418. :return: None
  2419. """
  2420. if hasattr(self, 'tcl'):
  2421. # self.tcl = None
  2422. # TODO we need to clean non default variables and procedures here
  2423. # new object cannot be used here as it will not remember values created for next passes,
  2424. # because tcl was execudted in old instance of TCL
  2425. pass
  2426. else:
  2427. self.tcl = tk.Tcl()
  2428. self.setup_shell()
  2429. self.log.debug("TCL Shell has been initialized.")
  2430. # TODO: This shouldn't be here.
  2431. class TclErrorException(Exception):
  2432. """
  2433. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2434. """
  2435. pass
  2436. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2437. """
  2438. Shows a message on the FlatCAM Shell
  2439. :param msg: Message to display.
  2440. :param show: Opens the shell.
  2441. :param error: Shows the message as an error.
  2442. :param warning: Shows the message as an warning.
  2443. :param success: Shows the message as an success.
  2444. :param selected: Indicate that something was selected on canvas
  2445. :return: None
  2446. """
  2447. if show:
  2448. self.ui.shell_dock.show()
  2449. try:
  2450. if error:
  2451. self.shell.append_error(msg + "\n")
  2452. elif warning:
  2453. self.shell.append_warning(msg + "\n")
  2454. elif success:
  2455. self.shell.append_success(msg + "\n")
  2456. elif selected:
  2457. self.shell.append_selected(msg + "\n")
  2458. else:
  2459. self.shell.append_output(msg + "\n")
  2460. except AttributeError:
  2461. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2462. def raise_tcl_unknown_error(self, unknownException):
  2463. """
  2464. Raise exception if is different type than TclErrorException
  2465. this is here mainly to show unknown errors inside TCL shell console.
  2466. :param unknownException:
  2467. :return:
  2468. """
  2469. if not isinstance(unknownException, self.TclErrorException):
  2470. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2471. else:
  2472. raise unknownException
  2473. def display_tcl_error(self, error, error_info=None):
  2474. """
  2475. Escape bracket [ with '\' otherwise there is error
  2476. "ERROR: missing close-bracket" instead of real error
  2477. :param error: it may be text or exception
  2478. :param error_info: Some informations about the error
  2479. :return: None
  2480. """
  2481. if isinstance(error, Exception):
  2482. exc_type, exc_value, exc_traceback = error_info
  2483. if not isinstance(error, self.TclErrorException):
  2484. show_trace = 1
  2485. else:
  2486. show_trace = int(self.defaults['global_verbose_error_level'])
  2487. if show_trace > 0:
  2488. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2489. trc_formated = []
  2490. for a in reversed(trc):
  2491. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2492. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2493. else:
  2494. text = "%s" % error
  2495. else:
  2496. text = error
  2497. text = text.replace('[', '\\[').replace('"', '\\"')
  2498. self.tcl.eval('return -code error "%s"' % text)
  2499. def raise_tcl_error(self, text):
  2500. """
  2501. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2502. :param text: text of error
  2503. :return: raise exception
  2504. """
  2505. self.display_tcl_error(text)
  2506. raise self.TclErrorException(text)
  2507. def exec_command(self, text):
  2508. """
  2509. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2510. Also handles execution in separated threads
  2511. :param text: FlatCAM TclCommand with parameters
  2512. :return: output if there was any
  2513. """
  2514. self.report_usage('exec_command')
  2515. result = self.exec_command_test(text, False)
  2516. # MS: added this method call so the geometry is updated once the TCL command is executed
  2517. self.plot_all()
  2518. return result
  2519. def exec_command_test(self, text, reraise=True):
  2520. """
  2521. Same as exec_command(...) with additional control over exceptions.
  2522. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2523. :param text: Input command
  2524. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2525. :return: Output from the command
  2526. """
  2527. text = str(text)
  2528. try:
  2529. self.shell.open_proccessing() # Disables input box.
  2530. result = self.tcl.eval(str(text))
  2531. if result != 'None':
  2532. self.shell.append_output(result + '\n')
  2533. except tk.TclError as e:
  2534. # This will display more precise answer if something in TCL shell fails
  2535. result = self.tcl.eval("set errorInfo")
  2536. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2537. self.shell.append_error('ERROR: ' + result + '\n')
  2538. # Show error in console and just return or in test raise exception
  2539. if reraise:
  2540. raise e
  2541. finally:
  2542. self.shell.close_proccessing()
  2543. pass
  2544. return result
  2545. # """
  2546. # Code below is unsused. Saved for later.
  2547. # """
  2548. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2549. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2550. # self.log.debug(parts)
  2551. # try:
  2552. # if parts[0] not in commands:
  2553. # self.shell.append_error("Unknown command\n")
  2554. # return
  2555. #
  2556. # #import inspect
  2557. # #inspect.getargspec(someMethod)
  2558. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2559. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2560. # self.shell.append_error(
  2561. # "Command %s takes %d arguments. %d given.\n" %
  2562. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2563. # )
  2564. # return
  2565. #
  2566. # cmdfcn = commands[parts[0]]["fcn"]
  2567. # cmdconv = commands[parts[0]]["converters"]
  2568. # if len(parts) - 1 > 0:
  2569. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2570. # else:
  2571. # retval = cmdfcn()
  2572. # retfcn = commands[parts[0]]["retfcn"]
  2573. # if retval and retfcn(retval):
  2574. # self.shell.append_output(retfcn(retval) + "\n")
  2575. #
  2576. # except Exception as e:
  2577. # #self.shell.append_error(''.join(traceback.format_exc()))
  2578. # #self.shell.append_error("?\n")
  2579. # self.shell.append_error(str(e) + "\n")
  2580. def info(self, msg):
  2581. """
  2582. Informs the user. Normally on the status bar, optionally
  2583. also on the shell.
  2584. :param msg: Text to write.
  2585. :return: None
  2586. """
  2587. # Type of message in brackets at the beginning of the message.
  2588. match = re.search("\[([^\]]+)\](.*)", msg)
  2589. if match:
  2590. level = match.group(1)
  2591. msg_ = match.group(2)
  2592. self.ui.fcinfo.set_status(str(msg_), level=level)
  2593. if level.lower() == "error":
  2594. self.shell_message(msg, error=True, show=True)
  2595. elif level.lower() == "warning":
  2596. self.shell_message(msg, warning=True, show=True)
  2597. elif level.lower() == "error_notcl":
  2598. self.shell_message(msg, error=True, show=False)
  2599. elif level.lower() == "warning_notcl":
  2600. self.shell_message(msg, warning=True, show=False)
  2601. elif level.lower() == "success":
  2602. self.shell_message(msg, success=True, show=False)
  2603. elif level.lower() == "selected":
  2604. self.shell_message(msg, selected=True, show=False)
  2605. else:
  2606. self.shell_message(msg, show=False)
  2607. else:
  2608. self.ui.fcinfo.set_status(str(msg), level="info")
  2609. # make sure that if the message is to clear the infobar with a space
  2610. # is not printed over and over on the shell
  2611. if msg != '':
  2612. self.shell_message(msg)
  2613. def restore_toolbar_view(self):
  2614. """
  2615. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2616. was saved in the defaults dictionary.
  2617. :return: None
  2618. """
  2619. tb = self.defaults["global_toolbar_view"]
  2620. if tb & 1:
  2621. self.ui.toolbarfile.setVisible(True)
  2622. else:
  2623. self.ui.toolbarfile.setVisible(False)
  2624. if tb & 2:
  2625. self.ui.toolbargeo.setVisible(True)
  2626. else:
  2627. self.ui.toolbargeo.setVisible(False)
  2628. if tb & 4:
  2629. self.ui.toolbarview.setVisible(True)
  2630. else:
  2631. self.ui.toolbarview.setVisible(False)
  2632. if tb & 8:
  2633. self.ui.toolbartools.setVisible(True)
  2634. else:
  2635. self.ui.toolbartools.setVisible(False)
  2636. if tb & 16:
  2637. self.ui.exc_edit_toolbar.setVisible(True)
  2638. else:
  2639. self.ui.exc_edit_toolbar.setVisible(False)
  2640. if tb & 32:
  2641. self.ui.geo_edit_toolbar.setVisible(True)
  2642. else:
  2643. self.ui.geo_edit_toolbar.setVisible(False)
  2644. if tb & 64:
  2645. self.ui.grb_edit_toolbar.setVisible(True)
  2646. else:
  2647. self.ui.grb_edit_toolbar.setVisible(False)
  2648. if tb & 128:
  2649. self.ui.snap_toolbar.setVisible(True)
  2650. else:
  2651. self.ui.snap_toolbar.setVisible(False)
  2652. if tb & 256:
  2653. self.ui.toolbarshell.setVisible(True)
  2654. else:
  2655. self.ui.toolbarshell.setVisible(False)
  2656. def load_defaults(self, filename):
  2657. """
  2658. Loads the aplication's default settings from current_defaults.FlatConfig into
  2659. ``self.defaults``.
  2660. :return: None
  2661. """
  2662. try:
  2663. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2664. options = f.read()
  2665. f.close()
  2666. except IOError:
  2667. self.log.error("Could not load defaults file.")
  2668. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2669. # in case the defaults file can't be loaded, show all toolbars
  2670. self.defaults["global_toolbar_view"] = 511
  2671. return
  2672. try:
  2673. defaults = json.loads(options)
  2674. except:
  2675. # in case the defaults file can't be loaded, show all toolbars
  2676. self.defaults["global_toolbar_view"] = 511
  2677. e = sys.exc_info()[0]
  2678. App.log.error(str(e))
  2679. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2680. return
  2681. self.defaults.update(defaults)
  2682. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2683. # restore the toolbar view
  2684. self.restore_toolbar_view()
  2685. def on_import_preferences(self):
  2686. """
  2687. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2688. ``self.defaults``.
  2689. :return: None
  2690. """
  2691. self.report_usage("on_import_preferences")
  2692. App.log.debug("on_import_preferences()")
  2693. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2694. try:
  2695. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2696. directory=self.data_path,
  2697. filter=filter_)
  2698. except TypeError:
  2699. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2700. filter=filter_)
  2701. filename = str(filename)
  2702. if filename == "":
  2703. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2704. else:
  2705. try:
  2706. f = open(filename)
  2707. options = f.read()
  2708. f.close()
  2709. except IOError:
  2710. self.log.error("Could not load defaults file.")
  2711. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2712. return
  2713. try:
  2714. defaults_from_file = json.loads(options)
  2715. except Exception as e:
  2716. e = sys.exc_info()[0]
  2717. App.log.error(str(e))
  2718. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2719. return
  2720. self.defaults.update(defaults_from_file)
  2721. self.on_preferences_edited()
  2722. self.inform.emit(_("[success] Imported Defaults from %s") % filename)
  2723. def on_export_preferences(self):
  2724. """
  2725. Save the defaults dictionary to a file.
  2726. :return: None
  2727. """
  2728. self.report_usage("on_export_preferences")
  2729. App.log.debug("on_export_preferences()")
  2730. defaults_file_content = None
  2731. self.date = str(datetime.today()).rpartition('.')[0]
  2732. self.date = ''.join(c for c in self.date if c not in ':-')
  2733. self.date = self.date.replace(' ', '_')
  2734. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2735. try:
  2736. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2737. caption=_("Export FlatCAM Preferences"),
  2738. directory=self.data_path + '/preferences_' + self.date,
  2739. filter=filter__
  2740. )
  2741. except TypeError:
  2742. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2743. filter=filter__)
  2744. filename = str(filename)
  2745. defaults_from_file = {}
  2746. if filename == "":
  2747. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2748. return
  2749. else:
  2750. try:
  2751. f = open(filename, 'w')
  2752. defaults_file_content = f.read()
  2753. f.close()
  2754. except PermissionError:
  2755. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  2756. "Most likely another app is holding the file open and not accessible."))
  2757. return
  2758. except IOError:
  2759. App.log.debug('Creating a new preferences file ...')
  2760. f = open(filename, 'w')
  2761. json.dump({}, f)
  2762. f.close()
  2763. except:
  2764. e = sys.exc_info()[0]
  2765. App.log.error("Could not load defaults file.")
  2766. App.log.error(str(e))
  2767. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2768. return
  2769. try:
  2770. defaults_from_file = json.loads(defaults_file_content)
  2771. except:
  2772. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2773. # Update options
  2774. self.defaults_read_form()
  2775. defaults_from_file.update(self.defaults)
  2776. self.propagate_defaults(silent=True)
  2777. # Save update options
  2778. try:
  2779. f = open(filename, "w")
  2780. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2781. f.close()
  2782. except:
  2783. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2784. return
  2785. if self.defaults["global_open_style"] is False:
  2786. self.file_opened.emit("preferences", filename)
  2787. self.file_saved.emit("preferences", filename)
  2788. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2789. def on_preferences_open_folder(self):
  2790. """
  2791. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2792. :return: None
  2793. """
  2794. self.report_usage("on_preferences_open_folder()")
  2795. if sys.platform == 'win32':
  2796. subprocess.Popen('explorer %s' % self.data_path)
  2797. elif sys.platform == 'darwin':
  2798. os.system('open "%s"' % self.data_path)
  2799. else:
  2800. subprocess.Popen(['xdg-open', self.data_path])
  2801. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2802. def save_geometry(self, x, y, width, height, notebook_width):
  2803. """
  2804. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2805. launch of the application.
  2806. :param x: X position of the main window
  2807. :param y: Y position of the main window
  2808. :param width: width of the main window
  2809. :param height: height of the main window
  2810. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2811. :return: None
  2812. """
  2813. self.defaults["global_def_win_x"] = x
  2814. self.defaults["global_def_win_y"] = y
  2815. self.defaults["global_def_win_w"] = width
  2816. self.defaults["global_def_win_h"] = height
  2817. self.defaults["global_def_notebook_width"] = notebook_width
  2818. self.save_defaults()
  2819. def message_dialog(self, title, message, kind="info"):
  2820. """
  2821. Builds and show a custom QMessageBox to be used in FlatCAM.
  2822. :param title: title of the QMessageBox
  2823. :param message: message to be displayed
  2824. :param kind: type of QMessageBox; will display a specific icon.
  2825. :return:
  2826. """
  2827. icon = {"info": QtWidgets.QMessageBox.Information,
  2828. "warning": QtWidgets.QMessageBox.Warning,
  2829. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2830. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2831. dlg.setText(message)
  2832. dlg.exec_()
  2833. def register_recent(self, kind, filename):
  2834. """
  2835. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2836. dictionary.
  2837. :param kind: type of file that was opened
  2838. :param filename: the path and file name for the file that was opened
  2839. :return:
  2840. """
  2841. self.log.debug("register_recent()")
  2842. self.log.debug(" %s" % kind)
  2843. self.log.debug(" %s" % filename)
  2844. record = {'kind': str(kind), 'filename': str(filename)}
  2845. if record in self.recent:
  2846. return
  2847. if record in self.recent_projects:
  2848. return
  2849. if record['kind'] == 'project':
  2850. self.recent_projects.insert(0, record)
  2851. else:
  2852. self.recent.insert(0, record)
  2853. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2854. self.recent.pop()
  2855. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2856. self.recent_projects.pop()
  2857. try:
  2858. f = open(self.data_path + '/recent.json', 'w')
  2859. except IOError:
  2860. App.log.error("Failed to open recent items file for writing.")
  2861. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2862. return
  2863. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2864. f.close()
  2865. try:
  2866. fp = open(self.data_path + '/recent_projects.json', 'w')
  2867. except IOError:
  2868. App.log.error("Failed to open recent items file for writing.")
  2869. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent projects file for writing.'))
  2870. return
  2871. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2872. fp.close()
  2873. # Re-build the recent items menu
  2874. self.setup_recent_items()
  2875. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2876. """
  2877. Creates a new specialized FlatCAMObj and attaches it to the application,
  2878. this is, updates the GUI accordingly, any other records and plots it.
  2879. This method is thread-safe.
  2880. Notes:
  2881. * If the name is in use, the self.collection will modify it
  2882. when appending it to the collection. There is no need to handle
  2883. name conflicts here.
  2884. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2885. :type kind: str
  2886. :param name: Name for the object.
  2887. :type name: str
  2888. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2889. The function is called with 2 parameters: the new object and the App instance.
  2890. :type initialize: function
  2891. :param active:
  2892. :param fit:
  2893. :param plot: If to plot the resulting object
  2894. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2895. self.colleaction
  2896. :return: None
  2897. :rtype: None
  2898. """
  2899. App.log.debug("new_object()")
  2900. obj_plot = plot
  2901. obj_autoselected = autoselected
  2902. t0 = time.time() # Debug
  2903. # ## Create object
  2904. classdict = {
  2905. "gerber": FlatCAMGerber,
  2906. "excellon": FlatCAMExcellon,
  2907. "cncjob": FlatCAMCNCjob,
  2908. "geometry": FlatCAMGeometry
  2909. }
  2910. App.log.debug("Calling object constructor...")
  2911. obj = classdict[kind](name)
  2912. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2913. # Set options from "Project options" form
  2914. self.options_read_form()
  2915. # IMPORTANT
  2916. # The key names in defaults and options dictionary's are not random:
  2917. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2918. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2919. # the options from project options form into the self.options. After that, below, depending on the type of
  2920. # object that is created, it will strip the name of the object and the underline (if the original key was
  2921. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2922. # "toolchange"
  2923. for option in self.options:
  2924. if option.find(kind + "_") == 0:
  2925. oname = option[len(kind) + 1:]
  2926. obj.options[oname] = self.options[option]
  2927. obj.isHovering = False
  2928. obj.notHovering = True
  2929. # Initialize as per user request
  2930. # User must take care to implement initialize
  2931. # in a thread-safe way as is is likely that we
  2932. # have been invoked in a separate thread.
  2933. t1 = time.time()
  2934. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2935. try:
  2936. return_value = initialize(obj, self)
  2937. except Exception as e:
  2938. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2939. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2940. msg += traceback.format_exc()
  2941. self.inform.emit(msg)
  2942. # if str(e) == "Empty Geometry":
  2943. # self.inform.emit("[ERROR_NOTCL] )
  2944. # else:
  2945. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2946. return "fail"
  2947. t2 = time.time()
  2948. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2949. if return_value == 'fail':
  2950. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2951. return "fail"
  2952. # Check units and convert if necessary
  2953. # This condition CAN be true because initialize() can change obj.units
  2954. if self.options["units"].upper() != obj.units.upper():
  2955. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2956. obj.convert_units(self.options["units"])
  2957. t3 = time.time()
  2958. self.log.debug("%f seconds converting units." % (t3 - t2))
  2959. # Create the bounding box for the object and then add the results to the obj.options
  2960. try:
  2961. xmin, ymin, xmax, ymax = obj.bounds()
  2962. obj.options['xmin'] = xmin
  2963. obj.options['ymin'] = ymin
  2964. obj.options['xmax'] = xmax
  2965. obj.options['ymax'] = ymax
  2966. except Exception as e:
  2967. log.warning("The object has no bounds properties. %s" % str(e))
  2968. return "fail"
  2969. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2970. # Move the object to the main thread and let the app know that it is available.
  2971. obj.moveToThread(self.main_thread)
  2972. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2973. return obj
  2974. def new_excellon_object(self):
  2975. """
  2976. Creates a new, blank Excellon object.
  2977. :return: None
  2978. """
  2979. self.report_usage("new_excellon_object()")
  2980. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2981. def new_geometry_object(self):
  2982. """
  2983. Creates a new, blank and single-tool Geometry object.
  2984. :return: None
  2985. """
  2986. self.report_usage("new_geometry_object()")
  2987. def initialize(obj, self):
  2988. obj.multitool = False
  2989. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2990. def new_gerber_object(self):
  2991. """
  2992. Creates a new, blank Gerber object.
  2993. :return: None
  2994. """
  2995. self.report_usage("new_gerber_object()")
  2996. def initialize(grb_obj, self):
  2997. grb_obj.multitool = False
  2998. grb_obj.source_file = []
  2999. grb_obj.multigeo = False
  3000. grb_obj.follow = False
  3001. grb_obj.apertures = {}
  3002. grb_obj.solid_geometry = []
  3003. try:
  3004. grb_obj.options['xmin'] = 0
  3005. grb_obj.options['ymin'] = 0
  3006. grb_obj.options['xmax'] = 0
  3007. grb_obj.options['ymax'] = 0
  3008. except KeyError:
  3009. pass
  3010. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3011. def on_object_created(self, obj, plot, autoselect):
  3012. """
  3013. Event callback for object creation.
  3014. It will add the new object to the collection. After that it will plot the object in a threaded way
  3015. :param obj: The newly created FlatCAM object.
  3016. :param plot: if the newly create object t obe plotted
  3017. :param autoselect: if the newly created object to be autoselected after creation
  3018. :return: None
  3019. """
  3020. t0 = time.time() # DEBUG
  3021. self.log.debug("on_object_created()")
  3022. # The Collection might change the name if there is a collision
  3023. self.collection.append(obj)
  3024. # after adding the object to the collection always update the list of objects that are in the collection
  3025. self.all_objects_list = self.collection.get_list()
  3026. # self.inform.emit('[selected] %s created & selected: %s' %
  3027. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3028. if obj.kind == 'gerber':
  3029. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3030. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3031. elif obj.kind == 'excellon':
  3032. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3033. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3034. elif obj.kind == 'cncjob':
  3035. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3036. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3037. elif obj.kind == 'geometry':
  3038. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3039. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3040. # update the SHELL auto-completer model with the name of the new object
  3041. self.myKeywords.append(obj.options['name'])
  3042. self.shell._edit.set_model_data(self.myKeywords)
  3043. self.ui.code_editor.set_model_data(self.myKeywords)
  3044. if autoselect:
  3045. # select the just opened object but deselect the previous ones
  3046. self.collection.set_all_inactive()
  3047. self.collection.set_active(obj.options["name"])
  3048. else:
  3049. self.collection.set_all_inactive()
  3050. # here it is done the object plotting
  3051. def worker_task(t_obj):
  3052. with self.proc_container.new(_("Plotting")):
  3053. if isinstance(t_obj, FlatCAMCNCjob):
  3054. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3055. else:
  3056. t_obj.plot()
  3057. t1 = time.time() # DEBUG
  3058. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3059. self.object_plotted.emit(t_obj)
  3060. # Send to worker
  3061. # self.worker.add_task(worker_task, [self])
  3062. if plot is True:
  3063. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3064. def on_object_changed(self, obj):
  3065. """
  3066. Called whenever the geometry of the object was changed in some way.
  3067. This require the update of it's bounding values so it can be the selected on canvas.
  3068. Update the bounding box data from obj.options
  3069. :param obj: the object that was changed
  3070. :return: None
  3071. """
  3072. xmin, ymin, xmax, ymax = obj.bounds()
  3073. obj.options['xmin'] = xmin
  3074. obj.options['ymin'] = ymin
  3075. obj.options['xmax'] = xmax
  3076. obj.options['ymax'] = ymax
  3077. log.debug("Object changed, updating the bounding box data on self.options")
  3078. # delete the old selection shape
  3079. self.delete_selection_shape()
  3080. self.should_we_save = True
  3081. def on_object_plotted(self, obj):
  3082. """
  3083. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3084. :param obj: object to be fit into view
  3085. :return: None
  3086. """
  3087. self.on_zoom_fit(None)
  3088. def options_read_form(self):
  3089. """
  3090. Same as it's equivalent from the defaults.
  3091. self.options use to store the preferences per project. No longer used.
  3092. :return: None
  3093. """
  3094. for option in self.options_form_fields:
  3095. self.options[option] = self.options_form_fields[option].get_value()
  3096. def options_write_form(self):
  3097. """
  3098. Same as it's equivalent from the defaults.
  3099. self.options use to store the preferences per project. No longer used.
  3100. :return: None
  3101. """
  3102. for option in self.options:
  3103. self.options_write_form_field(option)
  3104. def options_write_form_field(self, field):
  3105. """
  3106. Same as it's equivalent from the defaults.
  3107. self.options use to store the preferences per project. No longer used.
  3108. :return: None
  3109. """
  3110. try:
  3111. self.options_form_fields[field].set_value(self.options[field])
  3112. except KeyError:
  3113. # Changed from error to debug. This allows to have data stored
  3114. # which is not user-editable.
  3115. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3116. pass
  3117. def on_about(self):
  3118. """
  3119. Displays the "about" dialog found in the Menu --> Help.
  3120. :return: None
  3121. """
  3122. self.report_usage("on_about")
  3123. version = self.version
  3124. version_date = self.version_date
  3125. beta = self.beta
  3126. class AboutDialog(QtWidgets.QDialog):
  3127. def __init__(self, parent=None):
  3128. QtWidgets.QDialog.__init__(self, parent)
  3129. # Icon and title
  3130. self.setWindowIcon(parent.app_icon)
  3131. self.setWindowTitle("FlatCAM")
  3132. layout1 = QtWidgets.QVBoxLayout()
  3133. self.setLayout(layout1)
  3134. layout2 = QtWidgets.QHBoxLayout()
  3135. layout1.addLayout(layout2)
  3136. logo = QtWidgets.QLabel()
  3137. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3138. layout2.addWidget(logo, stretch=0)
  3139. title = QtWidgets.QLabel(
  3140. _(
  3141. "<font size=8><B>FlatCAM</B></font><BR>"
  3142. "Version {version} {beta} ({date}) - {arch} <BR>"
  3143. "<BR>"
  3144. "2D Computer-Aided Printed Circuit Board<BR>"
  3145. "Manufacturing.<BR>"
  3146. "<BR>"
  3147. "<B> License: </B><BR>"
  3148. "Licensed under MIT license (2014 - 2019)"
  3149. "<BR>"
  3150. "by (c)Juan Pablo Caram <BR>"
  3151. "<BR>"
  3152. "<B> Programmers:</B><BR>"
  3153. "Denis Hayrullin<BR>"
  3154. "Kamil Sopko<BR>"
  3155. "Marius Stanciu<BR>"
  3156. "Matthieu Berthomé<BR>"
  3157. "and many others found "
  3158. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  3159. "<BR>"
  3160. "<B>Development</B> is done "
  3161. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3162. "<b>DOWNLOAD</B> area "
  3163. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3164. ""
  3165. ).format(version=version,
  3166. beta=('BETA' if beta else ''),
  3167. date=version_date,
  3168. arch=platform.architecture()[0])
  3169. )
  3170. title.setOpenExternalLinks(True)
  3171. layout2.addWidget(title, stretch=1)
  3172. layout3 = QtWidgets.QHBoxLayout()
  3173. layout1.addLayout(layout3)
  3174. layout3.addStretch()
  3175. okbtn = QtWidgets.QPushButton(_("Close"))
  3176. layout3.addWidget(okbtn)
  3177. okbtn.clicked.connect(self.accept)
  3178. AboutDialog(self.ui).exec_()
  3179. def on_file_savedefaults(self):
  3180. """
  3181. Callback for menu item File->Save Defaults. Saves application default options
  3182. ``self.defaults`` to current_defaults.FlatConfig.
  3183. :return: None
  3184. """
  3185. self.save_defaults()
  3186. # def on_app_exit(self):
  3187. # self.report_usage("on_app_exit()")
  3188. #
  3189. # if self.collection.get_list():
  3190. # msgbox = QtWidgets.QMessageBox()
  3191. # # msgbox.setText("<B>Save changes ...</B>")
  3192. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3193. # "\n"
  3194. # "Do you want to Save the project?")
  3195. # msgbox.setWindowTitle("Save changes")
  3196. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3197. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3198. # QtWidgets.QMessageBox.Cancel)
  3199. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3200. #
  3201. # response = msgbox.exec_()
  3202. #
  3203. # if response == QtWidgets.QMessageBox.Yes:
  3204. # self.on_file_saveprojectas(thread=False)
  3205. # elif response == QtWidgets.QMessageBox.Cancel:
  3206. # return
  3207. # self.save_defaults()
  3208. # else:
  3209. # self.save_defaults()
  3210. # log.debug("Application defaults saved ... Exit event.")
  3211. # QtWidgets.qApp.quit()
  3212. def save_defaults(self, silent=False, data_path=None):
  3213. """
  3214. Saves application default options
  3215. ``self.defaults`` to current_defaults.FlatConfig file.
  3216. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3217. used at the next launch of the application.
  3218. :param silent: whether to display a message in status bar or not; boolean
  3219. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3220. When the application is portable it should be a mobile location.
  3221. :return: None
  3222. """
  3223. self.report_usage("save_defaults")
  3224. if data_path is None:
  3225. data_path = self.data_path
  3226. # Read options from file
  3227. try:
  3228. f = open(data_path + "/current_defaults.FlatConfig")
  3229. defaults_file_content = f.read()
  3230. f.close()
  3231. except:
  3232. e = sys.exc_info()[0]
  3233. App.log.error("Could not load defaults file.")
  3234. App.log.error(str(e))
  3235. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  3236. return
  3237. try:
  3238. defaults = json.loads(defaults_file_content)
  3239. except:
  3240. e = sys.exc_info()[0]
  3241. App.log.error("Failed to parse defaults file.")
  3242. App.log.error(str(e))
  3243. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  3244. return
  3245. # Update options
  3246. self.defaults_read_form()
  3247. defaults.update(self.defaults)
  3248. self.propagate_defaults(silent=True)
  3249. # Save the toolbar view
  3250. tb_status = 0
  3251. if self.ui.toolbarfile.isVisible():
  3252. tb_status += 1
  3253. if self.ui.toolbargeo.isVisible():
  3254. tb_status += 2
  3255. if self.ui.toolbarview.isVisible():
  3256. tb_status += 4
  3257. if self.ui.toolbartools.isVisible():
  3258. tb_status += 8
  3259. if self.ui.exc_edit_toolbar.isVisible():
  3260. tb_status += 16
  3261. if self.ui.geo_edit_toolbar.isVisible():
  3262. tb_status += 32
  3263. if self.ui.grb_edit_toolbar.isVisible():
  3264. tb_status += 64
  3265. if self.ui.snap_toolbar.isVisible():
  3266. tb_status += 128
  3267. if self.ui.toolbarshell.isVisible():
  3268. tb_status += 256
  3269. self.defaults["global_toolbar_view"] = tb_status
  3270. # Save update options
  3271. try:
  3272. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3273. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3274. f.close()
  3275. except:
  3276. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  3277. return
  3278. if not silent:
  3279. self.inform.emit(_("[success] Defaults saved."))
  3280. def save_factory_defaults(self, silent=False, data_path=None):
  3281. """
  3282. Saves application factory default options
  3283. ``self.defaults`` to factory_defaults.FlatConfig.
  3284. It's a one time job done just after the first install.
  3285. :param silent: whether to display a message in status bar or not; boolean
  3286. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3287. When the application is portable it should be a mobile location.
  3288. :return: None
  3289. """
  3290. self.report_usage("save_factory_defaults")
  3291. if data_path is None:
  3292. data_path = self.data_path
  3293. # Read options from file
  3294. try:
  3295. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3296. factory_defaults_file_content = f_f_def.read()
  3297. f_f_def.close()
  3298. except:
  3299. e = sys.exc_info()[0]
  3300. App.log.error("Could not load factory defaults file.")
  3301. App.log.error(str(e))
  3302. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  3303. return
  3304. try:
  3305. factory_defaults = json.loads(factory_defaults_file_content)
  3306. except:
  3307. e = sys.exc_info()[0]
  3308. App.log.error("Failed to parse factory defaults file.")
  3309. App.log.error(str(e))
  3310. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  3311. return
  3312. # Update options
  3313. self.defaults_read_form()
  3314. factory_defaults.update(self.defaults)
  3315. self.propagate_defaults(silent=True)
  3316. # Save update options
  3317. try:
  3318. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3319. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3320. f_f_def_s.close()
  3321. except:
  3322. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  3323. return
  3324. if silent is False:
  3325. self.inform.emit(_("Factory defaults saved."))
  3326. def final_save(self):
  3327. """
  3328. Callback for doing a preferences save to file whenever the application is about to quit.
  3329. If the project has changes, it will ask the user to save the project.
  3330. :return: None
  3331. """
  3332. if self.save_in_progress:
  3333. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  3334. return
  3335. if self.should_we_save and self.collection.get_list():
  3336. msgbox = QtWidgets.QMessageBox()
  3337. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3338. "\n"
  3339. "Do you want to Save the project?"))
  3340. msgbox.setWindowTitle(_("Save changes"))
  3341. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3342. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3343. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3344. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3345. msgbox.setDefaultButton(bt_yes)
  3346. msgbox.exec_()
  3347. response = msgbox.clickedButton()
  3348. if response == bt_yes:
  3349. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3350. elif response == bt_no:
  3351. self.quit_application()
  3352. elif response == bt_cancel:
  3353. return
  3354. else:
  3355. self.quit_application()
  3356. def quit_application(self):
  3357. """
  3358. Called (as a pyslot or not) when the application is quit.
  3359. :return: None
  3360. """
  3361. self.save_defaults()
  3362. log.debug("App.final_save() --> App Defaults saved.")
  3363. # save toolbar state to file
  3364. settings = QSettings("Open Source", "FlatCAM")
  3365. settings.setValue('saved_gui_state', self.ui.saveState())
  3366. settings.setValue('maximized_gui', self.ui.isMaximized())
  3367. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3368. settings.setValue('notebook_font_size',
  3369. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3370. settings.setValue('axis_font_size',
  3371. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3372. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3373. # This will write the setting to the platform specific storage.
  3374. del settings
  3375. log.debug("App.final_save() --> App UI state saved.")
  3376. QtWidgets.qApp.quit()
  3377. def on_portable_checked(self, state):
  3378. """
  3379. Callback called when the checkbox in Preferences GUI is checked.
  3380. It will set the application as portable by creating the preferences and recent files in the
  3381. 'config' folder found in the FlatCAM installation folder.
  3382. :param state: boolean, the state of the checkbox when clicked/checked
  3383. :return:
  3384. """
  3385. line_no = 0
  3386. data = None
  3387. if sys.platform != 'win32':
  3388. # this won't work in Linux or MacOS
  3389. return
  3390. # test if the app was frozen and choose the path for the configuration file
  3391. if getattr(sys, "frozen", False) is True:
  3392. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3393. else:
  3394. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3395. config_file = current_data_path + '\\configuration.txt'
  3396. try:
  3397. with open(config_file, 'r') as f:
  3398. try:
  3399. data = f.readlines()
  3400. except Exception as e:
  3401. log.debug('App.__init__() -->%s' % str(e))
  3402. return
  3403. except FileNotFoundError:
  3404. pass
  3405. for line in data:
  3406. line = line.strip('\n')
  3407. param = str(line).rpartition('=')
  3408. if param[0] == 'portable':
  3409. break
  3410. line_no += 1
  3411. if state:
  3412. data[line_no] = 'portable=True\n'
  3413. # create the new defauults files
  3414. # create current_defaults.FlatConfig file if there is none
  3415. try:
  3416. f = open(current_data_path + '/current_defaults.FlatConfig')
  3417. f.close()
  3418. except IOError:
  3419. App.log.debug('Creating empty current_defaults.FlatConfig')
  3420. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3421. json.dump({}, f)
  3422. f.close()
  3423. # create factory_defaults.FlatConfig file if there is none
  3424. try:
  3425. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3426. f.close()
  3427. except IOError:
  3428. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3429. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3430. json.dump({}, f)
  3431. f.close()
  3432. try:
  3433. f = open(current_data_path + '/recent.json')
  3434. f.close()
  3435. except IOError:
  3436. App.log.debug('Creating empty recent.json')
  3437. f = open(current_data_path + '/recent.json', 'w')
  3438. json.dump([], f)
  3439. f.close()
  3440. try:
  3441. fp = open(current_data_path + '/recent_projects.json')
  3442. fp.close()
  3443. except IOError:
  3444. App.log.debug('Creating empty recent_projects.json')
  3445. fp = open(current_data_path + '/recent_projects.json', 'w')
  3446. json.dump([], fp)
  3447. fp.close()
  3448. # save the current defaults to the new defaults file
  3449. self.save_defaults(silent=True, data_path=current_data_path)
  3450. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3451. else:
  3452. data[line_no] = 'portable=False\n'
  3453. with open(config_file, 'w') as f:
  3454. f.writelines(data)
  3455. def on_toggle_shell(self):
  3456. """
  3457. Toggle shell: if is visible close it, if it is closed then open it
  3458. :return:
  3459. """
  3460. self.report_usage("on_toggle_shell()")
  3461. if self.ui.shell_dock.isVisible():
  3462. self.ui.shell_dock.hide()
  3463. else:
  3464. self.ui.shell_dock.show()
  3465. def on_register_files(self, obj_type=None):
  3466. """
  3467. Called whenever there is a need to register file extensions with FlatCAM.
  3468. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3469. :param obj_type: the type of object to be register for.
  3470. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3471. :return: None
  3472. """
  3473. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3474. new_reg_path = 'Software\\Classes\\'
  3475. # find if the current user is admin
  3476. try:
  3477. is_admin = os.getuid() == 0
  3478. except AttributeError:
  3479. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3480. if is_admin is True:
  3481. root_path = winreg.HKEY_CLASSES_ROOT
  3482. else:
  3483. root_path = winreg.HKEY_CURRENT_USER
  3484. # create the keys
  3485. def set_reg(name, root_path, new_reg_path, value):
  3486. try:
  3487. winreg.CreateKey(root_path, new_reg_path)
  3488. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3489. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3490. return True
  3491. except WindowsError:
  3492. return False
  3493. # delete key in registry
  3494. def delete_reg(root_path, reg_path, key_to_del):
  3495. key_to_del_path = reg_path + key_to_del
  3496. try:
  3497. winreg.DeleteKey(root_path, key_to_del_path)
  3498. return True
  3499. except WindowsError:
  3500. return False
  3501. if obj_type is None or obj_type == 'excellon':
  3502. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3503. exc_list = [x for x in exc_list if x != '']
  3504. # register all keys in the Preferences window
  3505. for ext in exc_list:
  3506. new_k = new_reg_path + ext
  3507. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3508. # and unregister those that are no longer in the Preferences windows but are in the file
  3509. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3510. if ext not in exc_list:
  3511. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3512. # now write the updated extensions to the self.defaults
  3513. new_ext = ''
  3514. for ext in exc_list:
  3515. new_ext = new_ext + ext + ', '
  3516. self.defaults["fa_excellon"] = new_ext
  3517. self.inform.emit(_("[success] Selected Excellon file extensions registered with FlatCAM."))
  3518. if obj_type is None or obj_type == 'gcode':
  3519. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3520. gco_list = [x for x in gco_list if x != '']
  3521. # register all keys in the Preferences window
  3522. for ext in gco_list:
  3523. new_k = new_reg_path + ext
  3524. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3525. # and unregister those that are no longer in the Preferences windows but are in the file
  3526. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3527. if ext not in gco_list:
  3528. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3529. # now write the updated extensions to the self.defaults
  3530. new_ext = ''
  3531. for ext in gco_list:
  3532. new_ext = new_ext + ext + ', '
  3533. self.defaults["fa_gcode"] = new_ext
  3534. self.inform.emit(_("[success] Selected GCode file extensions registered with FlatCAM."))
  3535. if obj_type is None or obj_type == 'gerber':
  3536. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3537. grb_list = [x for x in grb_list if x != '']
  3538. # register all keys in the Preferences window
  3539. for ext in grb_list:
  3540. new_k = new_reg_path + ext
  3541. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3542. # and unregister those that are no longer in the Preferences windows but are in the file
  3543. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3544. if ext not in grb_list:
  3545. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3546. # now write the updated extensions to the self.defaults
  3547. new_ext = ''
  3548. for ext in grb_list:
  3549. new_ext = new_ext + ext + ', '
  3550. self.defaults["fa_gerber"] = new_ext
  3551. self.inform.emit(_("[success] Selected Gerber file extensions registered with FlatCAM."))
  3552. def on_edit_join(self, name=None):
  3553. """
  3554. Callback for Edit->Join. Joins the selected geometry objects into
  3555. a new one.
  3556. :return: None
  3557. """
  3558. self.report_usage("on_edit_join()")
  3559. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3560. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3561. tooldias = []
  3562. geo_type_list = set()
  3563. objs = self.collection.get_selected()
  3564. for obj in objs:
  3565. geo_type_list.add(obj.multigeo)
  3566. # if len(geo_type_list) == 1 means that all list elements are the same
  3567. if len(geo_type_list) != 1:
  3568. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  3569. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3570. "convert from one to another and retry joining \n"
  3571. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3572. "the result may not be what was expected. \n"
  3573. "Check the generated GCODE."))
  3574. return
  3575. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3576. if True in geo_type_list:
  3577. def initialize(obj, app):
  3578. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3579. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3580. for v in obj.tools.values():
  3581. v['data']['name'] = obj_name_multi
  3582. self.new_object("geometry", obj_name_multi, initialize)
  3583. else:
  3584. def initialize(obj, app):
  3585. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3586. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3587. for v in obj.tools.values():
  3588. v['data']['name'] = obj_name_single
  3589. self.new_object("geometry", obj_name_single, initialize)
  3590. self.should_we_save = True
  3591. def on_edit_join_exc(self):
  3592. """
  3593. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3594. a new Excellon.
  3595. :return: None
  3596. """
  3597. self.report_usage("on_edit_join_exc()")
  3598. objs = self.collection.get_selected()
  3599. for obj in objs:
  3600. if not isinstance(obj, FlatCAMExcellon):
  3601. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  3602. return
  3603. def initialize(obj, app):
  3604. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3605. self.new_object("excellon", 'Combo_Excellon', initialize)
  3606. self.should_we_save = True
  3607. def on_edit_join_grb(self):
  3608. """
  3609. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3610. a new Gerber object.
  3611. :return: None
  3612. """
  3613. self.report_usage("on_edit_join_grb()")
  3614. objs = self.collection.get_selected()
  3615. for obj in objs:
  3616. if not isinstance(obj, FlatCAMGerber):
  3617. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  3618. return
  3619. def initialize(obj, app):
  3620. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3621. self.new_object("gerber", 'Combo_Gerber', initialize)
  3622. self.should_we_save = True
  3623. def on_convert_singlegeo_to_multigeo(self):
  3624. """
  3625. Called for converting a Geometry object from single-geo to multi-geo.
  3626. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3627. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3628. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3629. the solid-geometry of that tool.
  3630. :return: None
  3631. """
  3632. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3633. obj = self.collection.get_active()
  3634. if obj is None:
  3635. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3636. return
  3637. if not isinstance(obj, FlatCAMGeometry):
  3638. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3639. return
  3640. obj.multigeo = True
  3641. for tooluid, dict_value in obj.tools.items():
  3642. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3643. if not isinstance(obj.solid_geometry, list):
  3644. obj.solid_geometry = [obj.solid_geometry]
  3645. obj.solid_geometry[:] = []
  3646. obj.plot()
  3647. self.should_we_save = True
  3648. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  3649. def on_convert_multigeo_to_singlegeo(self):
  3650. """
  3651. Called for converting a Geometry object from multi-geo to single-geo.
  3652. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3653. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3654. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3655. the solid-geometry of that tool.
  3656. :return: None
  3657. """
  3658. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3659. obj = self.collection.get_active()
  3660. if obj is None:
  3661. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3662. return
  3663. if not isinstance(obj, FlatCAMGeometry):
  3664. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3665. return
  3666. obj.multigeo = False
  3667. total_solid_geometry = []
  3668. for tooluid, dict_value in obj.tools.items():
  3669. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3670. # clear the original geometry
  3671. dict_value['solid_geometry'][:] = []
  3672. obj.solid_geometry = deepcopy(total_solid_geometry)
  3673. obj.plot()
  3674. self.should_we_save = True
  3675. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  3676. def on_options_dict_change(self, field):
  3677. """
  3678. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3679. current project. This feature is no longer used.
  3680. :param field:
  3681. :return:
  3682. """
  3683. self.options_write_form_field(field)
  3684. if field == "units":
  3685. self.set_screen_units(self.options['units'])
  3686. def on_defaults_dict_change(self, field):
  3687. """
  3688. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3689. Edit -> Preferences tab window.
  3690. :param field: the key of the self.defaults dictionary that was changed.
  3691. :return: None
  3692. """
  3693. self.defaults_write_form_field(field)
  3694. if field == "units":
  3695. self.set_screen_units(self.defaults['units'])
  3696. def set_screen_units(self, units):
  3697. """
  3698. Set the FlatCAM units on the status bar.
  3699. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3700. :return: None
  3701. """
  3702. self.ui.units_label.setText("[" + units.lower() + "]")
  3703. def on_toggle_units(self, no_pref=False):
  3704. """
  3705. Callback for the Units radio-button change in the Preferences tab.
  3706. Changes the application's default units adn for the project too.
  3707. If changing the project's units, the change propagates to all of
  3708. the objects in the project.
  3709. :return: None
  3710. """
  3711. self.report_usage("on_toggle_units")
  3712. if self.toggle_units_ignore:
  3713. return
  3714. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3715. # If option is the same, then ignore
  3716. if new_units == self.defaults["units"].upper():
  3717. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3718. return
  3719. # Options to scale
  3720. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3721. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3722. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3723. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3724. "excellon_z_pdepth",
  3725. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3726. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3727. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3728. "geometry_feedrate_probe",
  3729. 'cncjob_tooldia',
  3730. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3731. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3732. "tools_2sided_drilldia", "tools_film_boundary",
  3733. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3734. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3735. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3736. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3737. "tools_transform_offset_y",
  3738. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3739. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3740. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3741. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3742. 'global_gridx', 'global_gridy', 'global_snap_max']
  3743. def scale_options(sfactor):
  3744. for dim in dimensions:
  3745. if dim == 'excellon_toolchangexy':
  3746. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3747. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3748. coords_xy[0] *= sfactor
  3749. coords_xy[1] *= sfactor
  3750. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3751. elif dim == 'geometry_toolchangexy':
  3752. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3753. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3754. coords_xy[0] *= sfactor
  3755. coords_xy[1] *= sfactor
  3756. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3757. elif dim == 'geometry_cnctooldia':
  3758. tools_diameters = []
  3759. try:
  3760. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3761. tools_diameters = [eval(a) for a in tools_string if a != '']
  3762. except Exception as e:
  3763. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3764. self.options['geometry_cnctooldia'] = ''
  3765. for t in range(len(tools_diameters)):
  3766. tools_diameters[t] *= sfactor
  3767. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3768. elif dim == 'tools_ncctools':
  3769. ncctools = []
  3770. try:
  3771. tools_string = self.defaults["tools_ncctools"].split(",")
  3772. ncctools = [eval(a) for a in tools_string if a != '']
  3773. except Exception as e:
  3774. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3775. self.options['tools_ncctools'] = ''
  3776. for t in range(len(ncctools)):
  3777. ncctools[t] *= sfactor
  3778. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3779. elif dim == 'tools_solderpaste_tools':
  3780. sptools = []
  3781. try:
  3782. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3783. sptools = [eval(a) for a in tools_string if a != '']
  3784. except Exception as e:
  3785. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3786. self.options['tools_solderpaste_tools'] = ""
  3787. for t in range(len(sptools)):
  3788. sptools[t] *= sfactor
  3789. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3790. elif dim == 'tools_solderpaste_xy_toolchange':
  3791. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3792. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3793. sp_coords[0] *= sfactor
  3794. sp_coords[1] *= sfactor
  3795. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3796. elif dim == 'global_gridx' or dim == 'global_gridy':
  3797. if new_units == 'IN':
  3798. val = 0.1
  3799. try:
  3800. val = float(self.defaults[dim]) * sfactor
  3801. except Exception as e:
  3802. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3803. self.options[dim] = float('%.6f' % val)
  3804. else:
  3805. val = 0.1
  3806. try:
  3807. val = float(self.defaults[dim]) * sfactor
  3808. except Exception as e:
  3809. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3810. self.options[dim] = float('%.4f' % val)
  3811. else:
  3812. val = 0.1
  3813. try:
  3814. val = float(self.options[dim]) * sfactor
  3815. except Exception as e:
  3816. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3817. self.options[dim] = val
  3818. def scale_defaults(sfactor):
  3819. for dim in dimensions:
  3820. if dim == 'excellon_toolchangexy':
  3821. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3822. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3823. coords_xy[0] *= sfactor
  3824. coords_xy[1] *= sfactor
  3825. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3826. elif dim == 'geometry_toolchangexy':
  3827. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3828. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3829. coords_xy[0] *= sfactor
  3830. coords_xy[1] *= sfactor
  3831. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3832. elif dim == 'geometry_cnctooldia':
  3833. tools_diameters = []
  3834. try:
  3835. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3836. tools_diameters = [eval(a) for a in tools_string if a != '']
  3837. except Exception as e:
  3838. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3839. self.defaults['geometry_cnctooldia'] = ''
  3840. for t in range(len(tools_diameters)):
  3841. tools_diameters[t] *= sfactor
  3842. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3843. elif dim == 'tools_ncctools':
  3844. ncctools = []
  3845. try:
  3846. tools_string = self.defaults["tools_ncctools"].split(",")
  3847. ncctools = [eval(a) for a in tools_string if a != '']
  3848. except Exception as e:
  3849. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3850. self.defaults['tools_ncctools'] = ''
  3851. for t in range(len(ncctools)):
  3852. ncctools[t] *= sfactor
  3853. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3854. elif dim == 'tools_solderpaste_tools':
  3855. sptools = []
  3856. try:
  3857. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3858. sptools = [eval(a) for a in tools_string if a != '']
  3859. except Exception as e:
  3860. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3861. self.defaults['tools_solderpaste_tools'] = ""
  3862. for t in range(len(sptools)):
  3863. sptools[t] *= sfactor
  3864. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  3865. elif dim == 'tools_solderpaste_xy_toolchange':
  3866. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3867. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3868. sp_coords[0] *= sfactor
  3869. sp_coords[1] *= sfactor
  3870. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3871. elif dim == 'global_gridx' or dim == 'global_gridy':
  3872. if new_units == 'IN':
  3873. val = 0.1
  3874. try:
  3875. val = float(self.defaults[dim]) * sfactor
  3876. except Exception as e:
  3877. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3878. self.defaults[dim] = float('%.6f' % val)
  3879. else:
  3880. val = 0.1
  3881. try:
  3882. val = float(self.defaults[dim]) * sfactor
  3883. except Exception as e:
  3884. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3885. self.defaults[dim] = float('%.4f' % val)
  3886. else:
  3887. val = 0.1
  3888. try:
  3889. val = float(self.defaults[dim]) * sfactor
  3890. except Exception as e:
  3891. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3892. self.defaults[dim] = val
  3893. # The scaling factor depending on choice of units.
  3894. factor = 1/25.4
  3895. if new_units == 'MM':
  3896. factor = 25.4
  3897. # Changing project units. Warn user.
  3898. msgbox = QtWidgets.QMessageBox()
  3899. msgbox.setWindowTitle(_("Toggle Units"))
  3900. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3901. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3902. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  3903. "properties of all objects to be scaled accordingly.\nContinue?"))
  3904. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3905. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3906. msgbox.setDefaultButton(bt_ok)
  3907. msgbox.exec_()
  3908. response = msgbox.clickedButton()
  3909. if response == bt_ok:
  3910. if no_pref is False:
  3911. self.options_read_form()
  3912. scale_options(factor)
  3913. self.options_write_form()
  3914. self.defaults_read_form()
  3915. scale_defaults(factor)
  3916. self.defaults_write_form(fl_units=new_units)
  3917. # save the defaults to file, some may assume that the conversion is enough and it's not
  3918. self.on_save_button()
  3919. self.should_we_save = True
  3920. # change this only if the workspace is active
  3921. if self.defaults['global_workspace'] is True:
  3922. self.plotcanvas.draw_workspace()
  3923. # adjust the grid values on the main toolbar
  3924. dec = 6 if new_units == 'IN'else 4
  3925. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  3926. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  3927. if not self.ui.grid_gap_link_cb.isChecked():
  3928. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  3929. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  3930. for obj in self.collection.get_list():
  3931. obj.convert_units(new_units)
  3932. # make that the properties stored in the object are also updated
  3933. self.object_changed.emit(obj)
  3934. obj.build_ui()
  3935. current = self.collection.get_active()
  3936. if current is not None:
  3937. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3938. if not isinstance(current, FlatCAMGeometry):
  3939. current.to_form()
  3940. self.plot_all()
  3941. self.inform.emit(_("[success] Converted units to %s") % new_units)
  3942. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3943. self.set_screen_units(new_units)
  3944. else:
  3945. # Undo toggling
  3946. self.toggle_units_ignore = True
  3947. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3948. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3949. else:
  3950. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3951. self.toggle_units_ignore = False
  3952. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3953. self.options_read_form()
  3954. self.defaults_read_form()
  3955. def on_toggle_units_click(self):
  3956. try:
  3957. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3958. except (TypeError, AttributeError):
  3959. pass
  3960. if self.defaults["units"] == 'MM':
  3961. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3962. else:
  3963. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3964. self.on_toggle_units(no_pref=True)
  3965. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3966. lambda: self.on_toggle_units(no_pref=False))
  3967. def on_fullscreen(self):
  3968. self.report_usage("on_fullscreen()")
  3969. if self.toggle_fscreen is False:
  3970. if sys.platform == 'win32':
  3971. self.ui.showFullScreen()
  3972. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3973. tb.setVisible(False)
  3974. self.ui.splitter_left.setVisible(False)
  3975. self.toggle_fscreen = True
  3976. else:
  3977. if sys.platform == 'win32':
  3978. self.ui.showNormal()
  3979. self.restore_toolbar_view()
  3980. self.ui.splitter_left.setVisible(True)
  3981. self.toggle_fscreen = False
  3982. def on_toggle_plotarea(self):
  3983. self.report_usage("on_toggle_plotarea()")
  3984. try:
  3985. name = self.ui.plot_tab_area.widget(0).objectName()
  3986. except AttributeError:
  3987. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3988. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3989. self.ui.plot_tab_area.protectTab(0)
  3990. return
  3991. if name != 'plotarea':
  3992. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3993. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3994. self.ui.plot_tab_area.protectTab(0)
  3995. else:
  3996. self.ui.plot_tab_area.closeTab(0)
  3997. def on_toggle_notebook(self):
  3998. if self.ui.splitter.sizes()[0] == 0:
  3999. self.ui.splitter.setSizes([1, 1])
  4000. else:
  4001. self.ui.splitter.setSizes([0, 1])
  4002. def on_toggle_axis(self):
  4003. self.report_usage("on_toggle_axis()")
  4004. if self.toggle_axis is False:
  4005. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4006. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4007. self.plotcanvas.redraw()
  4008. self.toggle_axis = True
  4009. else:
  4010. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4011. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4012. self.plotcanvas.redraw()
  4013. self.toggle_axis = False
  4014. def on_toggle_grid(self):
  4015. self.report_usage("on_toggle_grid()")
  4016. self.ui.grid_snap_btn.trigger()
  4017. def on_options_combo_change(self, sel):
  4018. """
  4019. Called when the combo box to choose between application defaults and
  4020. project option changes value. The corresponding variables are
  4021. copied to the UI.
  4022. :param sel: The option index that was chosen.
  4023. :return: None
  4024. """
  4025. # combo_sel = self.ui.notebook.combo_options.get_active()
  4026. App.log.debug("Options --> %s" % sel)
  4027. # form = [self.defaults_form, self.options_form][sel]
  4028. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4029. if sel == 0:
  4030. self.gen_form = self.ui.general_defaults_form
  4031. self.ger_form = self.ui.gerber_defaults_form
  4032. self.exc_form = self.ui.excellon_defaults_form
  4033. self.geo_form = self.ui.geometry_defaults_form
  4034. self.cnc_form = self.ui.cncjob_defaults_form
  4035. self.tools_form = self.ui.tools_defaults_form
  4036. self.fa_form = self.ui.fa_defaults_form
  4037. elif sel == 1:
  4038. self.gen_form = self.ui.general_options_form
  4039. self.ger_form = self.ui.gerber_options_form
  4040. self.exc_form = self.ui.excellon_options_form
  4041. self.geo_form = self.ui.geometry_options_form
  4042. self.cnc_form = self.ui.cncjob_options_form
  4043. self.tools_form = self.ui.tools_options_form
  4044. self.fa_form = self.ui.fa_options_form
  4045. else:
  4046. return
  4047. try:
  4048. self.ui.general_scroll_area.takeWidget()
  4049. except:
  4050. self.log.debug("Nothing to remove")
  4051. self.ui.general_scroll_area.setWidget(self.gen_form)
  4052. self.gen_form.show()
  4053. try:
  4054. self.ui.gerber_scroll_area.takeWidget()
  4055. except:
  4056. self.log.debug("Nothing to remove")
  4057. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4058. self.ger_form.show()
  4059. try:
  4060. self.ui.excellon_scroll_area.takeWidget()
  4061. except:
  4062. self.log.debug("Nothing to remove")
  4063. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4064. self.exc_form.show()
  4065. try:
  4066. self.ui.geometry_scroll_area.takeWidget()
  4067. except:
  4068. self.log.debug("Nothing to remove")
  4069. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4070. self.geo_form.show()
  4071. try:
  4072. self.ui.cncjob_scroll_area.takeWidget()
  4073. except:
  4074. self.log.debug("Nothing to remove")
  4075. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4076. self.cnc_form.show()
  4077. try:
  4078. self.ui.tools_scroll_area.takeWidget()
  4079. except:
  4080. self.log.debug("Nothing to remove")
  4081. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4082. self.tools_form.show()
  4083. try:
  4084. self.ui.fa_scroll_area.takeWidget()
  4085. except:
  4086. self.log.debug("Nothing to remove")
  4087. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4088. self.fa_form.show()
  4089. self.log.debug("Finished GUI form initialization.")
  4090. # self.options2form()
  4091. def on_excellon_defaults_button(self):
  4092. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4093. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4094. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4095. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4096. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4097. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4098. log.debug("Excellon app defaults loaded ...")
  4099. def on_excellon_options_button(self):
  4100. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4101. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4102. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4103. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4104. self.options_form_fields["excellon_zeros"].set_value('L')
  4105. self.options_form_fields["excellon_units"].set_value('INCH')
  4106. log.debug("Excellon options defaults loaded ...")
  4107. # Setting plot colors handlers
  4108. def on_pf_color_entry(self):
  4109. self.defaults['global_plot_fill'] = \
  4110. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4111. self.defaults['global_plot_fill'][7:9]
  4112. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4113. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4114. def on_pf_color_button(self):
  4115. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4116. c_dialog = QtWidgets.QColorDialog()
  4117. plot_fill_color = c_dialog.getColor(initial=current_color)
  4118. if plot_fill_color.isValid() is False:
  4119. return
  4120. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4121. "background-color:%s" % str(plot_fill_color.name()))
  4122. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4123. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4124. self.defaults['global_plot_fill'] = new_val
  4125. def on_pf_color_spinner(self):
  4126. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4127. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4128. self.defaults['global_plot_fill'] = \
  4129. self.defaults['global_plot_fill'][:7] + \
  4130. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4131. self.defaults['global_plot_line'] = \
  4132. self.defaults['global_plot_line'][:7] + \
  4133. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4134. def on_pf_color_slider(self):
  4135. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4136. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4137. def on_pl_color_entry(self):
  4138. self.defaults['global_plot_line'] = \
  4139. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4140. self.defaults['global_plot_line'][7:9]
  4141. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4142. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4143. def on_pl_color_button(self):
  4144. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4145. # print(current_color)
  4146. c_dialog = QtWidgets.QColorDialog()
  4147. plot_line_color = c_dialog.getColor(initial=current_color)
  4148. if plot_line_color.isValid() is False:
  4149. return
  4150. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4151. "background-color:%s" % str(plot_line_color.name()))
  4152. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4153. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4154. self.defaults['global_plot_line'] = new_val_line
  4155. # Setting selection colors (left - right) handlers
  4156. def on_sf_color_entry(self):
  4157. self.defaults['global_sel_fill'] = \
  4158. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4159. self.defaults['global_sel_fill'][7:9]
  4160. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4161. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4162. def on_sf_color_button(self):
  4163. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4164. c_dialog = QtWidgets.QColorDialog()
  4165. plot_fill_color = c_dialog.getColor(initial=current_color)
  4166. if plot_fill_color.isValid() is False:
  4167. return
  4168. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4169. "background-color:%s" % str(plot_fill_color.name()))
  4170. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4171. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4172. self.defaults['global_sel_fill'] = new_val
  4173. def on_sf_color_spinner(self):
  4174. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4175. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4176. self.defaults['global_sel_fill'] = \
  4177. self.defaults['global_sel_fill'][:7] + \
  4178. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4179. self.defaults['global_sel_line'] = \
  4180. self.defaults['global_sel_line'][:7] + \
  4181. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4182. def on_sf_color_slider(self):
  4183. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4184. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4185. def on_sl_color_entry(self):
  4186. self.defaults['global_sel_line'] = \
  4187. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4188. self.defaults['global_sel_line'][7:9]
  4189. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4190. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4191. def on_sl_color_button(self):
  4192. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4193. c_dialog = QtWidgets.QColorDialog()
  4194. plot_line_color = c_dialog.getColor(initial=current_color)
  4195. if plot_line_color.isValid() is False:
  4196. return
  4197. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4198. "background-color:%s" % str(plot_line_color.name()))
  4199. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4200. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4201. self.defaults['global_sel_line'] = new_val_line
  4202. # Setting selection colors (right - left) handlers
  4203. def on_alt_sf_color_entry(self):
  4204. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4205. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4206. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4207. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4208. def on_alt_sf_color_button(self):
  4209. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4210. c_dialog = QtWidgets.QColorDialog()
  4211. plot_fill_color = c_dialog.getColor(initial=current_color)
  4212. if plot_fill_color.isValid() is False:
  4213. return
  4214. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4215. "background-color:%s" % str(plot_fill_color.name()))
  4216. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4217. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4218. self.defaults['global_alt_sel_fill'] = new_val
  4219. def on_alt_sf_color_spinner(self):
  4220. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4221. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4222. self.defaults['global_alt_sel_fill'] = \
  4223. self.defaults['global_alt_sel_fill'][:7] + \
  4224. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4225. self.defaults['global_alt_sel_line'] = \
  4226. self.defaults['global_alt_sel_line'][:7] + \
  4227. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4228. def on_alt_sf_color_slider(self):
  4229. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4230. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4231. def on_alt_sl_color_entry(self):
  4232. self.defaults['global_alt_sel_line'] = \
  4233. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4234. self.defaults['global_alt_sel_line'][7:9]
  4235. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4236. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4237. def on_alt_sl_color_button(self):
  4238. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4239. c_dialog = QtWidgets.QColorDialog()
  4240. plot_line_color = c_dialog.getColor(initial=current_color)
  4241. if plot_line_color.isValid() is False:
  4242. return
  4243. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4244. "background-color:%s" % str(plot_line_color.name()))
  4245. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4246. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4247. self.defaults['global_alt_sel_line'] = new_val_line
  4248. # Setting Editor colors
  4249. def on_draw_color_entry(self):
  4250. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4251. .draw_color_entry.get_value()
  4252. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4253. "background-color:%s" % str(self.defaults['global_draw_color']))
  4254. def on_draw_color_button(self):
  4255. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4256. c_dialog = QtWidgets.QColorDialog()
  4257. draw_color = c_dialog.getColor(initial=current_color)
  4258. if draw_color.isValid() is False:
  4259. return
  4260. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4261. "background-color:%s" % str(draw_color.name()))
  4262. new_val = str(draw_color.name())
  4263. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4264. self.defaults['global_draw_color'] = new_val
  4265. def on_sel_draw_color_entry(self):
  4266. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4267. .sel_draw_color_entry.get_value()
  4268. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4269. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4270. def on_sel_draw_color_button(self):
  4271. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4272. c_dialog = QtWidgets.QColorDialog()
  4273. sel_draw_color = c_dialog.getColor(initial=current_color)
  4274. if sel_draw_color.isValid() is False:
  4275. return
  4276. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4277. "background-color:%s" % str(sel_draw_color.name()))
  4278. new_val_sel = str(sel_draw_color.name())
  4279. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4280. self.defaults['global_sel_draw_color'] = new_val_sel
  4281. def on_proj_color_entry(self):
  4282. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4283. .proj_color_entry.get_value()
  4284. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4285. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4286. def on_proj_color_button(self):
  4287. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4288. c_dialog = QtWidgets.QColorDialog()
  4289. proj_color = c_dialog.getColor(initial=current_color)
  4290. if proj_color.isValid() is False:
  4291. return
  4292. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4293. "background-color:%s" % str(proj_color.name()))
  4294. new_val_sel = str(proj_color.name())
  4295. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4296. self.defaults['global_proj_item_color'] = new_val_sel
  4297. def on_proj_color_dis_entry(self):
  4298. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4299. .proj_color_dis_entry.get_value()
  4300. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4301. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4302. def on_proj_color_dis_button(self):
  4303. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4304. c_dialog = QtWidgets.QColorDialog()
  4305. proj_color = c_dialog.getColor(initial=current_color)
  4306. if proj_color.isValid() is False:
  4307. return
  4308. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4309. "background-color:%s" % str(proj_color.name()))
  4310. new_val_sel = str(proj_color.name())
  4311. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4312. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4313. def on_annotation_fontcolor_entry(self):
  4314. self.defaults['cncjob_annotation_fontcolor'] = \
  4315. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4316. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4317. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4318. def on_annotation_fontcolor_button(self):
  4319. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4320. c_dialog = QtWidgets.QColorDialog()
  4321. annotation_color = c_dialog.getColor(initial=current_color)
  4322. if annotation_color.isValid() is False:
  4323. return
  4324. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4325. "background-color:%s" % str(annotation_color.name()))
  4326. new_val_sel = str(annotation_color.name())
  4327. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4328. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4329. def on_notebook_tab_rmb_click(self, checked):
  4330. self.ui.notebook.set_detachable(val=checked)
  4331. self.defaults["global_tabs_detachable"] = checked
  4332. self.ui.plot_tab_area.set_detachable(val=checked)
  4333. self.defaults["global_tabs_detachable"] = checked
  4334. def on_deselect_all(self):
  4335. self.collection.set_all_inactive()
  4336. self.delete_selection_shape()
  4337. def on_workspace_modified(self):
  4338. self.save_defaults(silent=True)
  4339. self.plotcanvas.draw_workspace()
  4340. def on_workspace(self):
  4341. self.report_usage("on_workspace()")
  4342. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4343. self.plotcanvas.restore_workspace()
  4344. else:
  4345. self.plotcanvas.delete_workspace()
  4346. self.save_defaults(silent=True)
  4347. def on_workspace_menu(self):
  4348. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4349. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4350. else:
  4351. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4352. self.on_workspace()
  4353. def on_layout(self, index=None, lay=None):
  4354. self.report_usage("on_layout()")
  4355. if lay:
  4356. current_layout = lay
  4357. else:
  4358. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4359. settings = QSettings("Open Source", "FlatCAM")
  4360. settings.setValue('layout', current_layout)
  4361. # This will write the setting to the platform specific storage.
  4362. del settings
  4363. # first remove the toolbars:
  4364. try:
  4365. self.ui.removeToolBar(self.ui.toolbarfile)
  4366. self.ui.removeToolBar(self.ui.toolbargeo)
  4367. self.ui.removeToolBar(self.ui.toolbarview)
  4368. self.ui.removeToolBar(self.ui.toolbarshell)
  4369. self.ui.removeToolBar(self.ui.toolbartools)
  4370. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4371. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4372. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4373. self.ui.removeToolBar(self.ui.snap_toolbar)
  4374. self.ui.removeToolBar(self.ui.toolbarshell)
  4375. except Exception as e:
  4376. pass
  4377. if current_layout == 'standard':
  4378. # ## TOOLBAR INSTALLATION # ##
  4379. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4380. self.ui.toolbarfile.setObjectName('File_TB')
  4381. self.ui.addToolBar(self.ui.toolbarfile)
  4382. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4383. self.ui.toolbargeo.setObjectName('Edit_TB')
  4384. self.ui.addToolBar(self.ui.toolbargeo)
  4385. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4386. self.ui.toolbarview.setObjectName('View_TB')
  4387. self.ui.addToolBar(self.ui.toolbarview)
  4388. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4389. self.ui.toolbarshell.setObjectName('Shell_TB')
  4390. self.ui.addToolBar(self.ui.toolbarshell)
  4391. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4392. self.ui.toolbartools.setObjectName('Tools_TB')
  4393. self.ui.addToolBar(self.ui.toolbartools)
  4394. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4395. self.ui.exc_edit_toolbar.setVisible(False)
  4396. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4397. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4398. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4399. self.ui.geo_edit_toolbar.setVisible(False)
  4400. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4401. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4402. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4403. self.ui.grb_edit_toolbar.setVisible(False)
  4404. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4405. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4406. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4407. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4408. # self.ui.snap_toolbar.setMaximumHeight(30)
  4409. self.ui.addToolBar(self.ui.snap_toolbar)
  4410. self.ui.corner_snap_btn.setVisible(False)
  4411. self.ui.snap_magnet.setVisible(False)
  4412. elif current_layout == 'compact':
  4413. # ## TOOLBAR INSTALLATION # ##
  4414. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4415. self.ui.toolbarfile.setObjectName('File_TB')
  4416. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4417. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4418. self.ui.toolbargeo.setObjectName('Edit_TB')
  4419. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4420. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4421. self.ui.toolbarview.setObjectName('View_TB')
  4422. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  4423. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4424. self.ui.toolbarshell.setObjectName('Shell_TB')
  4425. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4426. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4427. self.ui.toolbartools.setObjectName('Tools_TB')
  4428. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4429. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4430. # self.ui.geo_edit_toolbar.setVisible(False)
  4431. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4432. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4433. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4434. # self.ui.grb_edit_toolbar.setVisible(False)
  4435. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4436. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4437. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4438. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4439. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4440. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4441. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4442. self.ui.snap_toolbar.setMaximumHeight(30)
  4443. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4444. self.ui.corner_snap_btn.setVisible(True)
  4445. self.ui.snap_magnet.setVisible(True)
  4446. # add all the actions to the toolbars
  4447. self.ui.populate_toolbars()
  4448. # reconnect all the signals to the toolbar actions
  4449. self.connect_toolbar_signals()
  4450. self.ui.grid_snap_btn.setChecked(True)
  4451. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4452. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4453. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4454. self.ui.grid_gap_link_cb.setChecked(True)
  4455. def on_cnc_custom_parameters(self, signal_text):
  4456. if signal_text == 'Parameters':
  4457. return
  4458. else:
  4459. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4460. def on_save_button(self):
  4461. log.debug("App.on_save_button() --> Saving preferences to file.")
  4462. self.preferences_changed_flag = False
  4463. self.save_defaults(silent=False)
  4464. # load the defaults so they are updated into the app
  4465. self.load_defaults(filename='current_defaults')
  4466. # Re-fresh project options
  4467. self.on_options_app2project()
  4468. # save the notebook font size
  4469. settings = QSettings("Open Source", "FlatCAM")
  4470. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4471. settings.setValue('notebook_font_size', fsize)
  4472. # save the axis font size
  4473. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4474. settings.setValue('axis_font_size', g_fsize)
  4475. # This will write the setting to the platform specific storage.
  4476. del settings
  4477. def handlePrint(self):
  4478. self.report_usage("handlePrint()")
  4479. dialog = QtPrintSupport.QPrintDialog()
  4480. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4481. self.ui.code_editor.document().print_(dialog.printer())
  4482. def handlePreview(self):
  4483. self.report_usage("handlePreview()")
  4484. dialog = QtPrintSupport.QPrintPreviewDialog()
  4485. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4486. dialog.exec_()
  4487. def handleTextChanged(self):
  4488. # enable = not self.ui.code_editor.document().isEmpty()
  4489. # self.ui.buttonPrint.setEnabled(enable)
  4490. # self.ui.buttonPreview.setEnabled(enable)
  4491. pass
  4492. def handleOpen(self, filt=None):
  4493. self.report_usage("handleOpen()")
  4494. if filt:
  4495. _filter_ = filt
  4496. else:
  4497. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4498. "All Files (*.*)"
  4499. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4500. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4501. if path:
  4502. file = QtCore.QFile(path)
  4503. if file.open(QtCore.QIODevice.ReadOnly):
  4504. stream = QtCore.QTextStream(file)
  4505. self.gcode_edited = stream.readAll()
  4506. self.ui.code_editor.setPlainText(self.gcode_edited)
  4507. file.close()
  4508. def handleSaveGCode(self, name=None, filt=None):
  4509. self.report_usage("handleSaveGCode()")
  4510. if filt:
  4511. _filter_ = filt
  4512. else:
  4513. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4514. "All Files (*.*)"
  4515. if name:
  4516. obj_name = name
  4517. else:
  4518. try:
  4519. obj_name = self.collection.get_active().options['name']
  4520. except AttributeError:
  4521. obj_name = 'file'
  4522. if filt is None:
  4523. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4524. try:
  4525. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4526. caption=_("Export G-Code ..."),
  4527. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4528. filter=_filter_
  4529. )[0])
  4530. except TypeError:
  4531. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4532. if filename == "":
  4533. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  4534. return
  4535. else:
  4536. try:
  4537. my_gcode = self.ui.code_editor.toPlainText()
  4538. with open(filename, 'w') as f:
  4539. for line in my_gcode:
  4540. f.write(line)
  4541. except FileNotFoundError:
  4542. self.inform.emit(_("[WARNING] No such file or directory"))
  4543. return
  4544. except PermissionError:
  4545. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  4546. "Most likely another app is holding the file open and not accessible."))
  4547. return
  4548. # Just for adding it to the recent files list.
  4549. if self.defaults["global_open_style"] is False:
  4550. self.file_opened.emit("cncjob", filename)
  4551. self.file_saved.emit("cncjob", filename)
  4552. self.inform.emit(_("Saved to: %s") % filename)
  4553. def handleFindGCode(self):
  4554. self.report_usage("handleFindGCode()")
  4555. flags = QtGui.QTextDocument.FindCaseSensitively
  4556. text_to_be_found = self.ui.entryFind.get_value()
  4557. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4558. if r is False:
  4559. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4560. def handleReplaceGCode(self):
  4561. self.report_usage("handleReplaceGCode()")
  4562. old = self.ui.entryFind.get_value()
  4563. new = self.ui.entryReplace.get_value()
  4564. if self.ui.sel_all_cb.isChecked():
  4565. while True:
  4566. cursor = self.ui.code_editor.textCursor()
  4567. cursor.beginEditBlock()
  4568. flags = QtGui.QTextDocument.FindCaseSensitively
  4569. # self.ui.editor is the QPlainTextEdit
  4570. r = self.ui.code_editor.find(str(old), flags)
  4571. if r:
  4572. qc = self.ui.code_editor.textCursor()
  4573. if qc.hasSelection():
  4574. qc.insertText(new)
  4575. else:
  4576. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4577. break
  4578. # Mark end of undo block
  4579. cursor.endEditBlock()
  4580. else:
  4581. cursor = self.ui.code_editor.textCursor()
  4582. cursor.beginEditBlock()
  4583. qc = self.ui.code_editor.textCursor()
  4584. if qc.hasSelection():
  4585. qc.insertText(new)
  4586. # Mark end of undo block
  4587. cursor.endEditBlock()
  4588. def on_tool_add_keypress(self):
  4589. # ## Current application units in Upper Case
  4590. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4591. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4592. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4593. if notebook_widget_name == 'selected_tab':
  4594. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4595. # Tool add works for Geometry only if Advanced is True in Preferences
  4596. if self.defaults["global_app_level"] == 'a':
  4597. tool_add_popup = FCInputDialog(title="New Tool ...",
  4598. text='Enter a Tool Diameter:',
  4599. min=0.0000, max=99.9999, decimals=4)
  4600. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4601. val, ok = tool_add_popup.get_value()
  4602. if ok:
  4603. if float(val) == 0:
  4604. self.inform.emit(
  4605. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4606. return
  4607. self.collection.get_active().on_tool_add(dia=float(val))
  4608. else:
  4609. self.inform.emit(
  4610. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4611. else:
  4612. msgbox = QtWidgets.QMessageBox()
  4613. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4614. "Go to Preferences -> General - Show Advanced Options."))
  4615. msgbox.setWindowTitle("Tool adding ...")
  4616. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4617. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4618. msgbox.setDefaultButton(bt_ok)
  4619. msgbox.exec_()
  4620. # work only if the notebook tab on focus is the Tools_Tab
  4621. if notebook_widget_name == 'tool_tab':
  4622. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4623. tool_add_popup = FCInputDialog(title="New Tool ...",
  4624. text='Enter a Tool Diameter:',
  4625. min=0.0000, max=99.9999, decimals=4)
  4626. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4627. val, ok = tool_add_popup.get_value()
  4628. # and only if the tool is NCC Tool
  4629. if tool_widget == self.ncclear_tool.toolName:
  4630. if ok:
  4631. if float(val) == 0:
  4632. self.inform.emit(
  4633. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4634. return
  4635. self.ncclear_tool.on_tool_add(dia=float(val))
  4636. else:
  4637. self.inform.emit(
  4638. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4639. # and only if the tool is Paint Area Tool
  4640. elif tool_widget == self.paint_tool.toolName:
  4641. if ok:
  4642. if float(val) == 0:
  4643. self.inform.emit(
  4644. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4645. return
  4646. self.paint_tool.on_tool_add(dia=float(val))
  4647. else:
  4648. self.inform.emit(
  4649. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4650. # and only if the tool is Solder Paste Dispensing Tool
  4651. elif tool_widget == self.paste_tool.toolName:
  4652. if ok:
  4653. if float(val) == 0:
  4654. self.inform.emit(
  4655. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4656. return
  4657. self.paste_tool.on_tool_add(dia=float(val))
  4658. else:
  4659. self.inform.emit(
  4660. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4661. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4662. # See description bellow.
  4663. def on_delete_keypress(self):
  4664. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4665. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4666. if notebook_widget_name == 'selected_tab':
  4667. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4668. self.collection.get_active().on_tool_delete()
  4669. # work only if the notebook tab on focus is the Tools_Tab
  4670. elif notebook_widget_name == 'tool_tab':
  4671. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4672. # and only if the tool is NCC Tool
  4673. if tool_widget == self.ncclear_tool.toolName:
  4674. self.ncclear_tool.on_tool_delete()
  4675. # and only if the tool is Paint Tool
  4676. elif tool_widget == self.paint_tool.toolName:
  4677. self.paint_tool.on_tool_delete()
  4678. # and only if the tool is Solder Paste Dispensing Tool
  4679. elif tool_widget == self.paste_tool.toolName:
  4680. self.paste_tool.on_tool_delete()
  4681. else:
  4682. self.on_delete()
  4683. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4684. # some screens you have to be careful where you hover with your mouse.
  4685. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4686. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4687. # Complicated, I know :)
  4688. def on_delete(self):
  4689. """
  4690. Delete the currently selected FlatCAMObjs.
  4691. :return: None
  4692. """
  4693. self.report_usage("on_delete()")
  4694. response = None
  4695. bt_ok = None
  4696. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4697. # a geometry object before we update it.
  4698. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4699. and self.grb_editor.editor_active is False:
  4700. if self.defaults["global_delete_confirmation"] is True:
  4701. msgbox = QtWidgets.QMessageBox()
  4702. msgbox.setWindowTitle(_("Delete objects"))
  4703. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4704. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4705. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4706. "the selected objects?"))
  4707. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4708. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4709. msgbox.setDefaultButton(bt_ok)
  4710. msgbox.exec_()
  4711. response = msgbox.clickedButton()
  4712. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4713. if self.collection.get_active():
  4714. self.log.debug("App.on_delete()")
  4715. while self.collection.get_active():
  4716. obj_active = self.collection.get_active()
  4717. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4718. if isinstance(obj_active, FlatCAMGerber):
  4719. for el in obj_active.mark_shapes:
  4720. obj_active.mark_shapes[el].clear(update=True)
  4721. obj_active.mark_shapes[el].enabled = False
  4722. obj_active.mark_shapes[el] = None
  4723. elif isinstance(obj_active, FlatCAMCNCjob):
  4724. try:
  4725. obj_active.annotation.clear(update=True)
  4726. obj_active.annotation.enabled = False
  4727. except AttributeError:
  4728. pass
  4729. self.delete_first_selected()
  4730. self.inform.emit(_("Object(s) deleted ..."))
  4731. # make sure that the selection shape is deleted, too
  4732. self.delete_selection_shape()
  4733. else:
  4734. self.inform.emit(_("Failed. No object(s) selected..."))
  4735. else:
  4736. self.inform.emit(_("Save the work in Editor and try again ..."))
  4737. def delete_first_selected(self):
  4738. # Keep this for later
  4739. try:
  4740. sel_obj = self.collection.get_active()
  4741. name = sel_obj.options["name"]
  4742. except AttributeError:
  4743. self.log.debug("Nothing selected for deletion")
  4744. return
  4745. # Remove from dictionary
  4746. self.collection.delete_active()
  4747. # Clear form
  4748. self.setup_component_editor()
  4749. self.inform.emit("Object deleted: %s" % name)
  4750. def on_set_origin(self):
  4751. """
  4752. Set the origin to the left mouse click position
  4753. :return: None
  4754. """
  4755. # display the message for the user
  4756. # and ask him to click on the desired position
  4757. self.report_usage("on_set_origin()")
  4758. def origin_replot():
  4759. def worker_task():
  4760. with self.proc_container.new('%s...' % _("Plotting")):
  4761. for obj in self.collection.get_list():
  4762. obj.plot()
  4763. self.plotcanvas.fit_view()
  4764. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4765. def on_set_zero_click(event):
  4766. # this function will be available only for mouse left click
  4767. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  4768. if event.button == 1:
  4769. if self.grid_status() == True:
  4770. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4771. else:
  4772. pos = pos_canvas
  4773. x = 0 - pos[0]
  4774. y = 0 - pos[1]
  4775. def worker_task():
  4776. with self.proc_container.new(_("Setting Origin...")):
  4777. for obj in self.collection.get_list():
  4778. obj.offset((x, y))
  4779. self.object_changed.emit(obj)
  4780. # Update the object bounding box options
  4781. a, b, c, d = obj.bounds()
  4782. obj.options['xmin'] = a
  4783. obj.options['ymin'] = b
  4784. obj.options['xmax'] = c
  4785. obj.options['ymax'] = d
  4786. self.inform.emit(_('[success] Origin set ...'))
  4787. self.replot_signal.emit([])
  4788. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4789. self.plotcanvas.vis_disconnect('mouse_press', on_set_zero_click)
  4790. self.should_we_save = True
  4791. self.inform.emit(_('Click to set the origin ...'))
  4792. self.plotcanvas.vis_connect('mouse_press', on_set_zero_click)
  4793. # first disconnect it as it may have been used by something else
  4794. try:
  4795. self.replot_signal.disconnect()
  4796. except TypeError:
  4797. pass
  4798. self.replot_signal[list].connect(origin_replot)
  4799. def on_jump_to(self, custom_location=None, fit_center=True):
  4800. """
  4801. Jump to a location by setting the mouse cursor location
  4802. :return:
  4803. """
  4804. self.report_usage("on_jump_to()")
  4805. if not custom_location:
  4806. dia_box = Dialog_box(title=_("Jump to ..."),
  4807. label=_("Enter the coordinates in format X,Y:"),
  4808. icon=QtGui.QIcon('share/jump_to16.png'))
  4809. if dia_box.ok is True:
  4810. try:
  4811. location = eval(dia_box.location)
  4812. if not isinstance(location, tuple):
  4813. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4814. return
  4815. except:
  4816. return
  4817. else:
  4818. return
  4819. else:
  4820. location = custom_location
  4821. if fit_center:
  4822. self.plotcanvas.fit_center(loc=location)
  4823. cursor = QtGui.QCursor()
  4824. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4825. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  4826. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4827. self.inform.emit(_("[success] Done."))
  4828. return location
  4829. def on_copy_object(self):
  4830. self.report_usage("on_copy_object()")
  4831. def initialize(obj_init, app):
  4832. obj_init.solid_geometry = obj.solid_geometry
  4833. try:
  4834. obj_init.follow_geometry = obj.follow_geometry
  4835. except AttributeError:
  4836. pass
  4837. try:
  4838. obj_init.apertures = obj.apertures
  4839. except AttributeError:
  4840. pass
  4841. try:
  4842. if obj.tools:
  4843. obj_init.tools = obj.tools
  4844. except Exception as e:
  4845. log.debug("App.on_copy_object() --> %s" % str(e))
  4846. def initialize_excellon(obj_init, app):
  4847. obj_init.tools = obj.tools
  4848. # drills are offset, so they need to be deep copied
  4849. obj_init.drills = deepcopy(obj.drills)
  4850. # slots are offset, so they need to be deep copied
  4851. obj_init.slots = deepcopy(obj.slots)
  4852. obj_init.create_geometry()
  4853. for obj in self.collection.get_selected():
  4854. obj_name = obj.options["name"]
  4855. try:
  4856. if isinstance(obj, FlatCAMExcellon):
  4857. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4858. elif isinstance(obj, FlatCAMGerber):
  4859. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4860. elif isinstance(obj, FlatCAMGeometry):
  4861. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4862. except Exception as e:
  4863. return "Operation failed: %s" % str(e)
  4864. def on_copy_object2(self, custom_name):
  4865. def initialize_geometry(obj_init, app):
  4866. obj_init.solid_geometry = obj.solid_geometry
  4867. try:
  4868. obj_init.follow_geometry = obj.follow_geometry
  4869. except AttributeError:
  4870. pass
  4871. try:
  4872. obj_init.apertures = obj.apertures
  4873. except AttributeError:
  4874. pass
  4875. try:
  4876. if obj.tools:
  4877. obj_init.tools = obj.tools
  4878. except Exception as e:
  4879. log.debug("on_copy_object2() --> %s" % str(e))
  4880. def initialize_gerber(obj_init, app):
  4881. obj_init.solid_geometry = obj.solid_geometry
  4882. obj_init.apertures = deepcopy(obj.apertures)
  4883. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4884. def initialize_excellon(obj_init, app):
  4885. obj_init.tools = obj.tools
  4886. # drills are offset, so they need to be deep copied
  4887. obj_init.drills = deepcopy(obj.drills)
  4888. # slots are offset, so they need to be deep copied
  4889. obj_init.slots = deepcopy(obj.slots)
  4890. obj_init.create_geometry()
  4891. for obj in self.collection.get_selected():
  4892. obj_name = obj.options["name"]
  4893. try:
  4894. if isinstance(obj, FlatCAMExcellon):
  4895. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4896. elif isinstance(obj, FlatCAMGerber):
  4897. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4898. elif isinstance(obj, FlatCAMGeometry):
  4899. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4900. except Exception as e:
  4901. return "Operation failed: %s" % str(e)
  4902. def on_rename_object(self, text):
  4903. self.report_usage("on_rename_object()")
  4904. named_obj = self.collection.get_active()
  4905. for obj in named_obj:
  4906. if obj is list:
  4907. self.on_rename_object(text)
  4908. else:
  4909. try:
  4910. obj.options['name'] = text
  4911. except Exception as e:
  4912. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4913. def convert_any2geo(self):
  4914. self.report_usage("convert_any2geo()")
  4915. def initialize(obj_init, app):
  4916. obj_init.solid_geometry = obj.solid_geometry
  4917. try:
  4918. obj_init.follow_geometry = obj.follow_geometry
  4919. except AttributeError:
  4920. pass
  4921. try:
  4922. obj_init.apertures = obj.apertures
  4923. except AttributeError:
  4924. pass
  4925. try:
  4926. if obj.tools:
  4927. obj_init.tools = obj.tools
  4928. except AttributeError:
  4929. pass
  4930. def initialize_excellon(obj_init, app):
  4931. # objs = self.collection.get_selected()
  4932. # FlatCAMGeometry.merge(objs, obj)
  4933. solid_geo = []
  4934. for tool in obj.tools:
  4935. for geo in obj.tools[tool]['solid_geometry']:
  4936. solid_geo.append(geo)
  4937. obj_init.solid_geometry = deepcopy(solid_geo)
  4938. if not self.collection.get_selected():
  4939. log.warning("App.convert_any2geo --> No object selected")
  4940. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4941. return
  4942. for obj in self.collection.get_selected():
  4943. obj_name = obj.options["name"]
  4944. try:
  4945. if isinstance(obj, FlatCAMExcellon):
  4946. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4947. else:
  4948. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4949. except Exception as e:
  4950. return "Operation failed: %s" % str(e)
  4951. def convert_any2gerber(self):
  4952. self.report_usage("convert_any2gerber()")
  4953. def initialize_geometry(obj_init, app):
  4954. apertures = {}
  4955. apid = 0
  4956. apertures[str(apid)] = {}
  4957. apertures[str(apid)]['geometry'] = []
  4958. for obj_orig in obj.solid_geometry:
  4959. new_elem = dict()
  4960. new_elem['solid'] = obj_orig
  4961. new_elem['follow'] = obj_orig.exterior
  4962. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4963. apertures[str(apid)]['size'] = 0.0
  4964. apertures[str(apid)]['type'] = 'C'
  4965. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4966. obj_init.apertures = deepcopy(apertures)
  4967. def initialize_excellon(obj_init, app):
  4968. apertures = {}
  4969. apid = 10
  4970. for tool in obj.tools:
  4971. apertures[str(apid)] = {}
  4972. apertures[str(apid)]['geometry'] = []
  4973. for geo in obj.tools[tool]['solid_geometry']:
  4974. new_el = dict()
  4975. new_el['solid'] = geo
  4976. new_el['follow'] = geo.exterior
  4977. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4978. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4979. apertures[str(apid)]['type'] = 'C'
  4980. apid += 1
  4981. # create solid_geometry
  4982. solid_geometry = []
  4983. for apid in apertures:
  4984. for geo_el in apertures[apid]['geometry']:
  4985. solid_geometry.append(geo_el['solid'])
  4986. solid_geometry = MultiPolygon(solid_geometry)
  4987. solid_geometry = solid_geometry.buffer(0.0000001)
  4988. obj_init.solid_geometry = deepcopy(solid_geometry)
  4989. obj_init.apertures = deepcopy(apertures)
  4990. # clear the working objects (perhaps not necessary due of Python GC)
  4991. apertures.clear()
  4992. if not self.collection.get_selected():
  4993. log.warning("App.convert_any2gerber --> No object selected")
  4994. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4995. return
  4996. for obj in self.collection.get_selected():
  4997. obj_name = obj.options["name"]
  4998. try:
  4999. if isinstance(obj, FlatCAMExcellon):
  5000. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5001. elif isinstance(obj, FlatCAMGeometry):
  5002. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5003. else:
  5004. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5005. except Exception as e:
  5006. return "Operation failed: %s" % str(e)
  5007. def abort_all_tasks(self):
  5008. if self.abort_flag is False:
  5009. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5010. self.abort_flag = True
  5011. def app_is_idle(self):
  5012. if self.abort_flag:
  5013. self.inform.emit('[WARNING_NOTCL] %s' %
  5014. _("The current task was gracefully closed on user request..."))
  5015. self.abort_flag = False
  5016. def on_selectall(self):
  5017. self.report_usage("on_selectall()")
  5018. # delete the possible selection box around a possible selected object
  5019. self.delete_selection_shape()
  5020. for name in self.collection.get_names():
  5021. self.collection.set_active(name)
  5022. curr_sel_obj = self.collection.get_by_name(name)
  5023. # create the selection box around the selected object
  5024. if self.defaults['global_selection_shape'] is True:
  5025. self.draw_selection_shape(curr_sel_obj)
  5026. def on_preferences(self):
  5027. # add the tab if it was closed
  5028. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5029. # delete the absolute and relative position and messages in the infobar
  5030. self.ui.position_label.setText("")
  5031. self.ui.rel_position_label.setText("")
  5032. # Switch plot_area to preferences page
  5033. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5034. self.ui.show()
  5035. # this disconnect() is done so the slot will be connected only once
  5036. try:
  5037. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5038. except (TypeError, AttributeError):
  5039. pass
  5040. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5041. # detect changes in the preferences
  5042. for idx in range(self.ui.pref_tab_area.count()):
  5043. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5044. try:
  5045. try:
  5046. tb.textEdited.disconnect(self.on_preferences_edited)
  5047. except (TypeError, AttributeError):
  5048. pass
  5049. tb.textEdited.connect(self.on_preferences_edited)
  5050. except AttributeError:
  5051. pass
  5052. try:
  5053. try:
  5054. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5055. except (TypeError, AttributeError):
  5056. pass
  5057. tb.modificationChanged.connect(self.on_preferences_edited)
  5058. except AttributeError:
  5059. pass
  5060. try:
  5061. try:
  5062. tb.toggled.disconnect(self.on_preferences_edited)
  5063. except (TypeError, AttributeError):
  5064. pass
  5065. tb.toggled.connect(self.on_preferences_edited)
  5066. except AttributeError:
  5067. pass
  5068. try:
  5069. try:
  5070. tb.valueChanged.disconnect(self.on_preferences_edited)
  5071. except (TypeError, AttributeError):
  5072. pass
  5073. tb.valueChanged.connect(self.on_preferences_edited)
  5074. except AttributeError:
  5075. pass
  5076. try:
  5077. try:
  5078. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5079. except (TypeError, AttributeError):
  5080. pass
  5081. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5082. except AttributeError:
  5083. pass
  5084. def on_preferences_edited(self):
  5085. self.inform.emit(_("[WARNING_NOTCL] Preferences edited but not saved."))
  5086. self.preferences_changed_flag = True
  5087. def on_preferences_closed(self):
  5088. # disconnect
  5089. for idx in range(self.ui.pref_tab_area.count()):
  5090. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5091. try:
  5092. tb.textEdited.disconnect(self.on_preferences_edited)
  5093. except (TypeError, AttributeError):
  5094. pass
  5095. try:
  5096. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5097. except (TypeError, AttributeError):
  5098. pass
  5099. try:
  5100. tb.toggled.disconnect(self.on_preferences_edited)
  5101. except (TypeError, AttributeError):
  5102. pass
  5103. try:
  5104. tb.valueChanged.disconnect(self.on_preferences_edited)
  5105. except (TypeError, AttributeError):
  5106. pass
  5107. try:
  5108. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5109. except (TypeError, AttributeError):
  5110. pass
  5111. if self.preferences_changed_flag is True:
  5112. msgbox = QtWidgets.QMessageBox()
  5113. msgbox.setText(_("One or more values are changed.\n"
  5114. "Do you want to save the Preferences?"))
  5115. msgbox.setWindowTitle(_("Save Preferences"))
  5116. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5117. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5118. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5119. msgbox.setDefaultButton(bt_yes)
  5120. msgbox.exec_()
  5121. response = msgbox.clickedButton()
  5122. if response == bt_yes:
  5123. self.on_save_button()
  5124. self.inform.emit(_("[success] Preferences saved."))
  5125. else:
  5126. self.preferences_changed_flag = False
  5127. return
  5128. def on_flipy(self):
  5129. self.report_usage("on_flipy()")
  5130. obj_list = self.collection.get_selected()
  5131. xminlist = []
  5132. yminlist = []
  5133. xmaxlist = []
  5134. ymaxlist = []
  5135. if not obj_list:
  5136. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  5137. else:
  5138. try:
  5139. # first get a bounding box to fit all
  5140. for obj in obj_list:
  5141. xmin, ymin, xmax, ymax = obj.bounds()
  5142. xminlist.append(xmin)
  5143. yminlist.append(ymin)
  5144. xmaxlist.append(xmax)
  5145. ymaxlist.append(ymax)
  5146. # get the minimum x,y and maximum x,y for all objects selected
  5147. xminimal = min(xminlist)
  5148. yminimal = min(yminlist)
  5149. xmaximal = max(xmaxlist)
  5150. ymaximal = max(ymaxlist)
  5151. px = 0.5 * (xminimal + xmaximal)
  5152. py = 0.5 * (yminimal + ymaximal)
  5153. # execute mirroring
  5154. for obj in obj_list:
  5155. obj.mirror('X', [px, py])
  5156. obj.plot()
  5157. self.object_changed.emit(obj)
  5158. self.inform.emit(_("[success] Flip on Y axis done."))
  5159. except Exception as e:
  5160. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  5161. return
  5162. def on_flipx(self):
  5163. self.report_usage("on_flipx()")
  5164. obj_list = self.collection.get_selected()
  5165. xminlist = []
  5166. yminlist = []
  5167. xmaxlist = []
  5168. ymaxlist = []
  5169. if not obj_list:
  5170. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  5171. else:
  5172. try:
  5173. # first get a bounding box to fit all
  5174. for obj in obj_list:
  5175. xmin, ymin, xmax, ymax = obj.bounds()
  5176. xminlist.append(xmin)
  5177. yminlist.append(ymin)
  5178. xmaxlist.append(xmax)
  5179. ymaxlist.append(ymax)
  5180. # get the minimum x,y and maximum x,y for all objects selected
  5181. xminimal = min(xminlist)
  5182. yminimal = min(yminlist)
  5183. xmaximal = max(xmaxlist)
  5184. ymaximal = max(ymaxlist)
  5185. px = 0.5 * (xminimal + xmaximal)
  5186. py = 0.5 * (yminimal + ymaximal)
  5187. # execute mirroring
  5188. for obj in obj_list:
  5189. obj.mirror('Y', [px, py])
  5190. obj.plot()
  5191. self.object_changed.emit(obj)
  5192. self.inform.emit(_("[success] Flip on X axis done."))
  5193. except Exception as e:
  5194. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  5195. return
  5196. def on_rotate(self, silent=False, preset=None):
  5197. self.report_usage("on_rotate()")
  5198. obj_list = self.collection.get_selected()
  5199. xminlist = []
  5200. yminlist = []
  5201. xmaxlist = []
  5202. ymaxlist = []
  5203. if not obj_list:
  5204. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  5205. else:
  5206. if silent is False:
  5207. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5208. min=-360, max=360, decimals=4,
  5209. init_val=float(self.defaults['tools_transform_rotate']))
  5210. num, ok = rotatebox.get_value()
  5211. else:
  5212. num = preset
  5213. ok = True
  5214. if ok:
  5215. try:
  5216. # first get a bounding box to fit all
  5217. for obj in obj_list:
  5218. xmin, ymin, xmax, ymax = obj.bounds()
  5219. xminlist.append(xmin)
  5220. yminlist.append(ymin)
  5221. xmaxlist.append(xmax)
  5222. ymaxlist.append(ymax)
  5223. # get the minimum x,y and maximum x,y for all objects selected
  5224. xminimal = min(xminlist)
  5225. yminimal = min(yminlist)
  5226. xmaximal = max(xmaxlist)
  5227. ymaximal = max(ymaxlist)
  5228. px = 0.5 * (xminimal + xmaximal)
  5229. py = 0.5 * (yminimal + ymaximal)
  5230. for sel_obj in obj_list:
  5231. sel_obj.rotate(-float(num), point=(px, py))
  5232. sel_obj.plot()
  5233. self.object_changed.emit(sel_obj)
  5234. self.inform.emit(_("[success] Rotation done."))
  5235. except Exception as e:
  5236. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  5237. return
  5238. def on_skewx(self):
  5239. self.report_usage("on_skewx()")
  5240. obj_list = self.collection.get_selected()
  5241. xminlist = []
  5242. yminlist = []
  5243. if not obj_list:
  5244. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  5245. else:
  5246. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5247. min=-360, max=360, decimals=4,
  5248. init_val=float(self.defaults['tools_transform_skew_x']))
  5249. num, ok = skewxbox.get_value()
  5250. if ok:
  5251. # first get a bounding box to fit all
  5252. for obj in obj_list:
  5253. xmin, ymin, xmax, ymax = obj.bounds()
  5254. xminlist.append(xmin)
  5255. yminlist.append(ymin)
  5256. # get the minimum x,y and maximum x,y for all objects selected
  5257. xminimal = min(xminlist)
  5258. yminimal = min(yminlist)
  5259. for obj in obj_list:
  5260. obj.skew(num, 0, point=(xminimal, yminimal))
  5261. obj.plot()
  5262. self.object_changed.emit(obj)
  5263. self.inform.emit(_("[success] Skew on X axis done."))
  5264. def on_skewy(self):
  5265. self.report_usage("on_skewy()")
  5266. obj_list = self.collection.get_selected()
  5267. xminlist = []
  5268. yminlist = []
  5269. if not obj_list:
  5270. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  5271. else:
  5272. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5273. min=-360, max=360, decimals=4,
  5274. init_val=float(self.defaults['tools_transform_skew_y']))
  5275. num, ok = skewybox.get_value()
  5276. if ok:
  5277. # first get a bounding box to fit all
  5278. for obj in obj_list:
  5279. xmin, ymin, xmax, ymax = obj.bounds()
  5280. xminlist.append(xmin)
  5281. yminlist.append(ymin)
  5282. # get the minimum x,y and maximum x,y for all objects selected
  5283. xminimal = min(xminlist)
  5284. yminimal = min(yminlist)
  5285. for obj in obj_list:
  5286. obj.skew(0, num, point=(xminimal, yminimal))
  5287. obj.plot()
  5288. self.object_changed.emit(obj)
  5289. self.inform.emit(_("[success] Skew on Y axis done."))
  5290. def on_plots_updated(self):
  5291. """
  5292. Callback used to report when the plots have changed.
  5293. Adjust axes and zooms to fit.
  5294. :return: None
  5295. """
  5296. self.plotcanvas.update() # TODO: Need update canvas?
  5297. self.on_zoom_fit(None)
  5298. self.collection.update_view()
  5299. # self.inform.emit(_("Plots updated ..."))
  5300. # TODO: Rework toolbar 'clear', 'replot' functions
  5301. def on_toolbar_replot(self):
  5302. """
  5303. Callback for toolbar button. Re-plots all objects.
  5304. :return: None
  5305. """
  5306. self.report_usage("on_toolbar_replot")
  5307. self.log.debug("on_toolbar_replot()")
  5308. try:
  5309. self.collection.get_active().read_form()
  5310. except AttributeError:
  5311. self.log.debug("on_toolbar_replot(): AttributeError")
  5312. pass
  5313. self.plot_all()
  5314. def on_row_activated(self, index):
  5315. if index.isValid():
  5316. if index.internalPointer().parent_item != self.collection.root_item:
  5317. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5318. self.collection.on_item_activated(index)
  5319. def grid_status(self):
  5320. if self.ui.grid_snap_btn.isChecked():
  5321. return True
  5322. else:
  5323. return False
  5324. def populate_cmenu_grids(self):
  5325. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5326. self.ui.cmenu_gridmenu.clear()
  5327. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5328. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5329. grid_toggle.setCheckable(True)
  5330. if self.grid_status() == True:
  5331. grid_toggle.setChecked(True)
  5332. else:
  5333. grid_toggle.setChecked(False)
  5334. self.ui.cmenu_gridmenu.addSeparator()
  5335. for grid in sorted_list:
  5336. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5337. action.triggered.connect(self.set_grid)
  5338. self.ui.cmenu_gridmenu.addSeparator()
  5339. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5340. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5341. grid_add.triggered.connect(self.on_grid_add)
  5342. grid_delete.triggered.connect(self.on_grid_delete)
  5343. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5344. def set_grid(self):
  5345. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5346. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5347. def on_grid_add(self):
  5348. # ## Current application units in lower Case
  5349. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5350. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5351. text=_('Enter a Grid Value:'),
  5352. min=0.0000, max=99.9999, decimals=4)
  5353. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5354. val, ok = grid_add_popup.get_value()
  5355. if ok:
  5356. if float(val) == 0:
  5357. self.inform.emit(
  5358. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  5359. return
  5360. else:
  5361. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5362. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5363. self.inform.emit(
  5364. _("[success] New Grid added ..."))
  5365. else:
  5366. self.inform.emit(
  5367. _("[WARNING_NOTCL] Grid already exists ..."))
  5368. else:
  5369. self.inform.emit(
  5370. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  5371. def on_grid_delete(self):
  5372. # ## Current application units in lower Case
  5373. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5374. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5375. text='Enter a Grid Value:',
  5376. min=0.0000, max=99.9999, decimals=4)
  5377. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5378. val, ok = grid_del_popup.get_value()
  5379. if ok:
  5380. if float(val) == 0:
  5381. self.inform.emit(
  5382. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  5383. return
  5384. else:
  5385. try:
  5386. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5387. except ValueError:
  5388. self.inform.emit(
  5389. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  5390. return
  5391. self.inform.emit(
  5392. _("[success] Grid Value deleted ..."))
  5393. else:
  5394. self.inform.emit(
  5395. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  5396. def on_shortcut_list(self):
  5397. self.report_usage("on_shortcut_list()")
  5398. # add the tab if it was closed
  5399. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5400. # delete the absolute and relative position and messages in the infobar
  5401. self.ui.position_label.setText("")
  5402. self.ui.rel_position_label.setText("")
  5403. # Switch plot_area to preferences page
  5404. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5405. self.ui.show()
  5406. def on_select_tab(self, name):
  5407. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5408. if self.ui.splitter.sizes()[0] == 0:
  5409. self.ui.splitter.setSizes([1, 1])
  5410. else:
  5411. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5412. self.ui.splitter.setSizes([0, 1])
  5413. if name == 'project':
  5414. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5415. elif name == 'selected':
  5416. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5417. elif name == 'tool':
  5418. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5419. def on_copy_name(self):
  5420. self.report_usage("on_copy_name()")
  5421. obj = self.collection.get_active()
  5422. try:
  5423. name = obj.options["name"]
  5424. except AttributeError:
  5425. log.debug("on_copy_name() --> No object selected to copy it's name")
  5426. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  5427. return
  5428. self.clipboard.setText(name)
  5429. self.inform.emit(_("Name copied on clipboard ..."))
  5430. def on_mouse_click_over_plot(self, event):
  5431. """
  5432. Default actions are:
  5433. :param event: Contains information about the event, like which button
  5434. was clicked, the pixel coordinates and the axes coordinates.
  5435. :return: None
  5436. """
  5437. self.pos = []
  5438. # So it can receive key presses
  5439. self.plotcanvas.native.setFocus()
  5440. # Set the mouse button for panning
  5441. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5442. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5443. if self.grid_status() == True:
  5444. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5445. self.app_cursor.enabled = True
  5446. else:
  5447. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5448. self.app_cursor.enabled = False
  5449. try:
  5450. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5451. if event.button == 1:
  5452. # Reset here the relative coordinates so there is a new reference on the click position
  5453. if self.rel_point1 is None:
  5454. self.rel_point1 = self.pos
  5455. else:
  5456. self.rel_point2 = copy(self.rel_point1)
  5457. self.rel_point1 = self.pos
  5458. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5459. if modifiers == QtCore.Qt.ShiftModifier:
  5460. # do not auto open the Project Tab
  5461. self.click_noproject = True
  5462. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5463. self.inform.emit(_("[success] Coordinates copied to clipboard."))
  5464. return
  5465. self.on_mouse_move_over_plot(event, origin_click=True)
  5466. except Exception as e:
  5467. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5468. def on_double_click_over_plot(self, event):
  5469. self.doubleclick = True
  5470. def on_mouse_move_over_plot(self, event, origin_click=None):
  5471. """
  5472. Callback for the mouse motion event over the plot.
  5473. :param event: Contains information about the event.
  5474. :param origin_click
  5475. :return: None
  5476. """
  5477. # So it can receive key presses
  5478. self.plotcanvas.native.setFocus()
  5479. self.pos_jump = event.pos
  5480. self.ui.popMenu.mouse_is_panning = False
  5481. if not origin_click:
  5482. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5483. if event.button == 2 and event.is_dragging == 1:
  5484. self.ui.popMenu.mouse_is_panning = True
  5485. return
  5486. if self.rel_point1 is not None:
  5487. try: # May fail in case mouse not within axes
  5488. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5489. if self.grid_status() == True:
  5490. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5491. self.app_cursor.enabled = True
  5492. # Update cursor
  5493. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5494. else:
  5495. pos = (pos_canvas[0], pos_canvas[1])
  5496. self.app_cursor.enabled = False
  5497. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5498. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5499. dx = pos[0] - self.rel_point1[0]
  5500. dy = pos[1] - self.rel_point1[1]
  5501. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5502. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5503. self.mouse = [pos[0], pos[1]]
  5504. # if the mouse is moved and the LMB is clicked then the action is a selection
  5505. if event.is_dragging == 1 and event.button == 1:
  5506. self.delete_selection_shape()
  5507. if dx < 0:
  5508. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5509. face_color=self.defaults['global_alt_sel_fill'])
  5510. self.selection_type = False
  5511. else:
  5512. self.draw_moving_selection_shape(self.pos, pos)
  5513. self.selection_type = True
  5514. # hover effect - enabled in Preferences -> General -> GUI Settings
  5515. if self.defaults['global_hover']:
  5516. for obj in self.collection.get_list():
  5517. try:
  5518. # select the object(s) only if it is enabled (plotted)
  5519. if obj.options['plot']:
  5520. if obj not in self.collection.get_selected():
  5521. poly_obj = Polygon(
  5522. [(obj.options['xmin'], obj.options['ymin']),
  5523. (obj.options['xmax'], obj.options['ymin']),
  5524. (obj.options['xmax'], obj.options['ymax']),
  5525. (obj.options['xmin'], obj.options['ymax'])]
  5526. )
  5527. if Point(pos).within(poly_obj):
  5528. if obj.isHovering is False:
  5529. obj.isHovering = True
  5530. obj.notHovering = True
  5531. # create the selection box around the selected object
  5532. self.draw_hover_shape(obj, color='#d1e0e0')
  5533. else:
  5534. if obj.notHovering is True:
  5535. obj.notHovering = False
  5536. obj.isHovering = False
  5537. self.delete_hover_shape()
  5538. except:
  5539. # the Exception here will happen if we try to select on screen and we have an
  5540. # newly (and empty) just created Geometry or Excellon object that do not have the
  5541. # xmin, xmax, ymin, ymax options.
  5542. # In this case poly_obj creation (see above) will fail
  5543. pass
  5544. except:
  5545. self.ui.position_label.setText("")
  5546. self.ui.rel_position_label.setText("")
  5547. self.mouse = None
  5548. def on_mouse_click_release_over_plot(self, event):
  5549. """
  5550. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5551. and has been registered in ''self.__init__()''.
  5552. :param event: contains information about the event.
  5553. :return:
  5554. """
  5555. pos = 0, 0
  5556. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5557. if self.grid_status() == True:
  5558. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5559. else:
  5560. pos = (pos_canvas[0], pos_canvas[1])
  5561. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5562. # canvas menu
  5563. if event.button == 2: # right click
  5564. if self.ui.popMenu.mouse_is_panning is False:
  5565. self.cursor = QtGui.QCursor()
  5566. self.populate_cmenu_grids()
  5567. self.ui.popMenu.popup(self.cursor.pos())
  5568. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5569. # selection and then select a type of selection ("enclosing" or "touching")
  5570. try:
  5571. if event.button == 1: # left click
  5572. if self.doubleclick is True:
  5573. self.doubleclick = False
  5574. if self.collection.get_selected():
  5575. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5576. if self.ui.splitter.sizes()[0] == 0:
  5577. self.ui.splitter.setSizes([1, 1])
  5578. # delete the selection shape(S) as it may be in the way
  5579. self.delete_selection_shape()
  5580. self.delete_hover_shape()
  5581. else:
  5582. if self.selection_type is not None:
  5583. self.selection_area_handler(self.pos, pos, self.selection_type)
  5584. self.selection_type = None
  5585. else:
  5586. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5587. if key_modifier == QtCore.Qt.ShiftModifier:
  5588. mod_key = 'Shift'
  5589. elif key_modifier == QtCore.Qt.ControlModifier:
  5590. mod_key = 'Control'
  5591. else:
  5592. mod_key = None
  5593. if mod_key == self.defaults["global_mselect_key"]:
  5594. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5595. # deselect, and if it's not selected then it will be selected
  5596. # If there is no active command (self.command_active is None) then we check if we clicked
  5597. # on a object by checking the bounding limits against mouse click position
  5598. if self.command_active is None:
  5599. self.select_objects(key='CTRL')
  5600. self.delete_hover_shape()
  5601. else:
  5602. # If there is no active command (self.command_active is None) then we check if we clicked
  5603. # on a object by checking the bounding limits against mouse click position
  5604. if self.command_active is None:
  5605. self.select_objects()
  5606. self.delete_hover_shape()
  5607. except Exception as e:
  5608. log.warning("Error: %s" % str(e))
  5609. return
  5610. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5611. """
  5612. :param start_pos: mouse position when the selection LMB click was done
  5613. :param end_pos: mouse position when the left mouse button is released
  5614. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5615. :return:
  5616. """
  5617. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5618. self.delete_selection_shape()
  5619. for obj in self.collection.get_list():
  5620. try:
  5621. # select the object(s) only if it is enabled (plotted)
  5622. if obj.options['plot']:
  5623. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5624. (obj.options['xmax'], obj.options['ymin']),
  5625. (obj.options['xmax'], obj.options['ymax']),
  5626. (obj.options['xmin'], obj.options['ymax'])])
  5627. if sel_type is True:
  5628. if poly_obj.within(poly_selection):
  5629. # create the selection box around the selected object
  5630. if self.defaults['global_selection_shape'] is True:
  5631. self.draw_selection_shape(obj)
  5632. self.collection.set_active(obj.options['name'])
  5633. else:
  5634. if poly_selection.intersects(poly_obj):
  5635. # create the selection box around the selected object
  5636. if self.defaults['global_selection_shape'] is True:
  5637. self.draw_selection_shape(obj)
  5638. self.collection.set_active(obj.options['name'])
  5639. except Exception as e:
  5640. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5641. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5642. # In this case poly_obj creation (see above) will fail
  5643. log.debug("App.selection_area_handler() --> %s" % str(e))
  5644. def select_objects(self, key=None):
  5645. # list where we store the overlapped objects under our mouse left click position
  5646. objects_under_the_click_list = []
  5647. # Populate the list with the overlapped objects on the click position
  5648. curr_x, curr_y = self.pos
  5649. for obj in self.all_objects_list:
  5650. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5651. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5652. if obj.options['name'] not in objects_under_the_click_list:
  5653. if obj.options['plot']:
  5654. # add objects to the objects_under_the_click list only if the object is plotted
  5655. # (active and not disabled)
  5656. objects_under_the_click_list.append(obj.options['name'])
  5657. try:
  5658. # If there is no element in the overlapped objects list then make everyone inactive
  5659. # because we selected "nothing"
  5660. if not objects_under_the_click_list:
  5661. self.collection.set_all_inactive()
  5662. # delete the possible selection box around a possible selected object
  5663. self.delete_selection_shape()
  5664. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5665. # only when working on App
  5666. if self.call_source == 'app':
  5667. if self.click_noproject is False:
  5668. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5669. else:
  5670. # restore auto open the Project Tab
  5671. self.click_noproject = False
  5672. # delete any text in the status bar, implicitly the last object name that was selected
  5673. self.inform.emit("")
  5674. else:
  5675. self.call_source = 'app'
  5676. else:
  5677. # case when there is only an object under the click and we toggle it
  5678. if len(objects_under_the_click_list) == 1:
  5679. if self.collection.get_active() is None:
  5680. self.collection.set_active(objects_under_the_click_list[0])
  5681. # create the selection box around the selected object
  5682. curr_sel_obj = self.collection.get_active()
  5683. if self.defaults['global_selection_shape'] is True:
  5684. self.draw_selection_shape(curr_sel_obj)
  5685. # self.inform.emit('[selected] %s: %s selected' %
  5686. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5687. if curr_sel_obj.kind == 'gerber':
  5688. self.inform.emit(
  5689. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5690. color='green', name=str(curr_sel_obj.options['name'])))
  5691. elif curr_sel_obj.kind == 'excellon':
  5692. self.inform.emit(
  5693. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5694. color='brown', name=str(curr_sel_obj.options['name'])))
  5695. elif curr_sel_obj.kind == 'cncjob':
  5696. self.inform.emit(
  5697. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5698. color='blue', name=str(curr_sel_obj.options['name'])))
  5699. elif curr_sel_obj.kind == 'geometry':
  5700. self.inform.emit(
  5701. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5702. color='red', name=str(curr_sel_obj.options['name'])))
  5703. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5704. self.collection.set_all_inactive()
  5705. self.delete_selection_shape()
  5706. self.collection.set_active(objects_under_the_click_list[0])
  5707. # create the selection box around the selected object
  5708. curr_sel_obj = self.collection.get_active()
  5709. if self.defaults['global_selection_shape'] is True:
  5710. self.draw_selection_shape(curr_sel_obj)
  5711. # self.inform.emit('[selected] %s: %s selected' %
  5712. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5713. if curr_sel_obj.kind == 'gerber':
  5714. self.inform.emit(
  5715. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5716. color='green', name=str(curr_sel_obj.options['name'])))
  5717. elif curr_sel_obj.kind == 'excellon':
  5718. self.inform.emit(
  5719. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5720. color='brown', name=str(curr_sel_obj.options['name'])))
  5721. elif curr_sel_obj.kind == 'cncjob':
  5722. self.inform.emit(
  5723. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5724. color='blue', name=str(curr_sel_obj.options['name'])))
  5725. elif curr_sel_obj.kind == 'geometry':
  5726. self.inform.emit(
  5727. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5728. color='red', name=str(curr_sel_obj.options['name'])))
  5729. else:
  5730. self.collection.set_all_inactive()
  5731. self.delete_selection_shape()
  5732. if self.call_source == 'app':
  5733. # delete any text in the status bar, implicitly the last object name that was selected
  5734. self.inform.emit("")
  5735. else:
  5736. self.call_source = 'app'
  5737. else:
  5738. # If there is no selected object
  5739. # make active the first element of the overlapped objects list
  5740. if self.collection.get_active() is None:
  5741. self.collection.set_active(objects_under_the_click_list[0])
  5742. name_sel_obj = self.collection.get_active().options['name']
  5743. # In case that there is a selected object but it is not in the overlapped object list
  5744. # make that object inactive and activate the first element in the overlapped object list
  5745. if name_sel_obj not in objects_under_the_click_list:
  5746. self.collection.set_inactive(name_sel_obj)
  5747. name_sel_obj = objects_under_the_click_list[0]
  5748. self.collection.set_active(name_sel_obj)
  5749. else:
  5750. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5751. self.collection.set_all_inactive()
  5752. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5753. len(objects_under_the_click_list)])
  5754. curr_sel_obj = self.collection.get_active()
  5755. # delete the possible selection box around a possible selected object
  5756. self.delete_selection_shape()
  5757. # create the selection box around the selected object
  5758. if self.defaults['global_selection_shape'] is True:
  5759. self.draw_selection_shape(curr_sel_obj)
  5760. # self.inform.emit('[selected] %s: %s selected' %
  5761. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5762. if curr_sel_obj.kind == 'gerber':
  5763. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5764. color='green', name=str(curr_sel_obj.options['name'])))
  5765. elif curr_sel_obj.kind == 'excellon':
  5766. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5767. color='brown', name=str(curr_sel_obj.options['name'])))
  5768. elif curr_sel_obj.kind == 'cncjob':
  5769. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5770. color='blue', name=str(curr_sel_obj.options['name'])))
  5771. elif curr_sel_obj.kind == 'geometry':
  5772. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5773. color='red', name=str(curr_sel_obj.options['name'])))
  5774. # for obj in self.collection.get_list():
  5775. # obj.plot()
  5776. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5777. # TODO: on selected objects change the object colors and do not draw the selection box
  5778. # self.plotcanvas.update() # this updates the canvas
  5779. except Exception as e:
  5780. log.error("[ERROR] Something went bad. %s" % str(e))
  5781. return
  5782. def delete_hover_shape(self):
  5783. self.hover_shapes.clear()
  5784. self.hover_shapes.redraw()
  5785. def draw_hover_shape(self, sel_obj, color=None):
  5786. """
  5787. :param sel_obj: the object for which the hover shape must be drawn
  5788. :return:
  5789. """
  5790. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5791. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5792. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5793. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5794. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5795. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5796. hover_rect = hover_rect.buffer(-0.1)
  5797. hover_rect = hover_rect.buffer(0.2)
  5798. else:
  5799. hover_rect = hover_rect.buffer(-0.00393)
  5800. hover_rect = hover_rect.buffer(0.00787)
  5801. if color:
  5802. face = Color(color)
  5803. face.alpha = 0.2
  5804. outline = Color(color, alpha=0.8)
  5805. else:
  5806. face = Color(self.defaults['global_sel_fill'])
  5807. face.alpha = 0.2
  5808. outline = self.defaults['global_sel_line']
  5809. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5810. def delete_selection_shape(self):
  5811. self.move_tool.sel_shapes.clear()
  5812. self.move_tool.sel_shapes.redraw()
  5813. def draw_selection_shape(self, sel_obj, color=None):
  5814. """
  5815. :param sel_obj: the object for which the selection shape must be drawn
  5816. :return:
  5817. """
  5818. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5819. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5820. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5821. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5822. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5823. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5824. sel_rect = sel_rect.buffer(-0.1)
  5825. sel_rect = sel_rect.buffer(0.2)
  5826. else:
  5827. sel_rect = sel_rect.buffer(-0.00393)
  5828. sel_rect = sel_rect.buffer(0.00787)
  5829. if color:
  5830. face = Color(color, alpha=0.2)
  5831. outline = Color(color, alpha=0.8)
  5832. else:
  5833. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  5834. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  5835. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5836. color=outline,
  5837. face_color=face,
  5838. update=True,
  5839. layer=0,
  5840. tolerance=None))
  5841. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5842. """
  5843. :param old_coords: old coordinates
  5844. :param coords: new coordinates
  5845. :return:
  5846. """
  5847. if 'color' in kwargs:
  5848. color = kwargs['color']
  5849. else:
  5850. color = self.defaults['global_sel_line']
  5851. if 'face_color' in kwargs:
  5852. face_color = kwargs['face_color']
  5853. else:
  5854. face_color = self.defaults['global_sel_fill']
  5855. if 'face_alpha' in kwargs:
  5856. face_alpha = kwargs['face_alpha']
  5857. else:
  5858. face_alpha = 0.3
  5859. x0, y0 = old_coords
  5860. x1, y1 = coords
  5861. pt1 = (x0, y0)
  5862. pt2 = (x1, y0)
  5863. pt3 = (x1, y1)
  5864. pt4 = (x0, y1)
  5865. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5866. color_t = Color(face_color)
  5867. color_t.alpha = face_alpha
  5868. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5869. layer=0, tolerance=None)
  5870. def on_file_new_click(self):
  5871. if self.collection.get_list() and self.should_we_save:
  5872. msgbox = QtWidgets.QMessageBox()
  5873. # msgbox.setText("<B>Save changes ...</B>")
  5874. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5875. "Creating a New project will delete them.\n"
  5876. "Do you want to Save the project?"))
  5877. msgbox.setWindowTitle(_("Save changes"))
  5878. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5879. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5880. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5881. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5882. msgbox.setDefaultButton(bt_yes)
  5883. msgbox.exec_()
  5884. response = msgbox.clickedButton()
  5885. if response == bt_yes:
  5886. self.on_file_saveprojectas()
  5887. elif response == bt_cancel:
  5888. return
  5889. elif response == bt_no:
  5890. self.on_file_new()
  5891. else:
  5892. self.on_file_new()
  5893. self.inform.emit(_("[success] New Project created..."))
  5894. def on_file_new(self):
  5895. """
  5896. Callback for menu item File->New. Returns the application to its
  5897. startup state. This method is thread-safe.
  5898. :return: None
  5899. """
  5900. self.report_usage("on_file_new")
  5901. # Remove everything from memory
  5902. App.log.debug("on_file_new()")
  5903. if self.call_source != 'app':
  5904. self.editor2object(cleanup=True)
  5905. # ## EDITOR section
  5906. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  5907. self.exc_editor = FlatCAMExcEditor(self)
  5908. self.grb_editor = FlatCAMGrbEditor(self)
  5909. # Clear pool
  5910. self.clear_pool()
  5911. for obj in self.collection.get_list():
  5912. # delete shapes left drawn from mark shape_collections, if any
  5913. if isinstance(obj, FlatCAMGerber):
  5914. try:
  5915. obj.mark_shapes.enabled = False
  5916. obj.mark_shapes.clear(update=True)
  5917. except AttributeError:
  5918. pass
  5919. # also delete annotation shapes, if any
  5920. elif isinstance(obj, FlatCAMCNCjob):
  5921. try:
  5922. obj.annotation.enabled = False
  5923. obj.annotation.clear(update=True)
  5924. except AttributeError:
  5925. pass
  5926. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5927. self.init_tcl()
  5928. self.delete_selection_shape()
  5929. self.collection.delete_all()
  5930. self.setup_component_editor()
  5931. # Clear project filename
  5932. self.project_filename = None
  5933. # Load the application defaults
  5934. self.load_defaults(filename='current_defaults')
  5935. # Re-fresh project options
  5936. self.on_options_app2project()
  5937. # Init Tools
  5938. self.init_tools()
  5939. # Close any Tabs opened in the Plot Tab Area section
  5940. for index in range(self.ui.plot_tab_area.count()):
  5941. self.ui.plot_tab_area.closeTab(index)
  5942. # for whatever reason previous command does not close the last tab so I do it manually
  5943. self.ui.plot_tab_area.closeTab(0)
  5944. # # And then add again the Plot Area
  5945. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5946. self.ui.plot_tab_area.protectTab(0)
  5947. # take the focus of the Notebook on Project Tab.
  5948. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5949. self.set_ui_title(name=_("New Project - Not saved"))
  5950. def obj_properties(self):
  5951. self.report_usage("obj_properties()")
  5952. self.properties_tool.run(toggle=False)
  5953. def on_project_context_save(self):
  5954. obj = self.collection.get_active()
  5955. if type(obj) == FlatCAMGeometry:
  5956. self.on_file_exportdxf()
  5957. elif type(obj) == FlatCAMExcellon:
  5958. self.on_file_saveexcellon()
  5959. elif type(obj) == FlatCAMCNCjob:
  5960. obj.on_exportgcode_button_click()
  5961. elif type(obj) == FlatCAMGerber:
  5962. self.on_file_savegerber()
  5963. def obj_move(self):
  5964. self.report_usage("obj_move()")
  5965. self.move_tool.run(toggle=False)
  5966. def on_fileopengerber(self, checked=None, name=None):
  5967. """
  5968. File menu callback for opening a Gerber.
  5969. :return: None
  5970. """
  5971. self.report_usage("on_fileopengerber")
  5972. App.log.debug("on_fileopengerber()")
  5973. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5974. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5975. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  5976. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5977. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5978. "*.mil);;" \
  5979. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5980. "Allegro Files (*.art);;" \
  5981. "Mentor Files (*.pho *.gdo);;" \
  5982. "All Files (*.*)"
  5983. if name is None:
  5984. try:
  5985. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5986. directory=self.get_last_folder(),
  5987. filter=_filter_)
  5988. except TypeError:
  5989. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5990. filenames = [str(filename) for filename in filenames]
  5991. else:
  5992. filenames = [name]
  5993. if len(filenames) == 0:
  5994. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  5995. else:
  5996. for filename in filenames:
  5997. if filename != '':
  5998. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5999. def on_fileopenexcellon(self, checked=None, name=None):
  6000. """
  6001. File menu callback for opening an Excellon file.
  6002. :return: None
  6003. """
  6004. self.report_usage("on_fileopenexcellon")
  6005. App.log.debug("on_fileopenexcellon()")
  6006. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6007. "All Files (*.*)"
  6008. if name is None:
  6009. try:
  6010. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6011. directory=self.get_last_folder(),
  6012. filter=_filter_)
  6013. except TypeError:
  6014. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6015. filenames = [str(filename) for filename in filenames]
  6016. else:
  6017. filenames = [str(name)]
  6018. if len(filenames) == 0:
  6019. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  6020. else:
  6021. for filename in filenames:
  6022. if filename != '':
  6023. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6024. def on_fileopengcode(self, checked=None, name=None):
  6025. """
  6026. File menu call back for opening gcode.
  6027. :return: None
  6028. """
  6029. self.report_usage("on_fileopengcode")
  6030. App.log.debug("on_fileopengcode()")
  6031. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6032. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6033. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6034. "All Files (*.*)"
  6035. if name is None:
  6036. try:
  6037. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6038. directory=self.get_last_folder(),
  6039. filter=_filter_)
  6040. except TypeError:
  6041. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6042. filenames = [str(filename) for filename in filenames]
  6043. else:
  6044. filenames = [name]
  6045. if len(filenames) == 0:
  6046. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  6047. else:
  6048. for filename in filenames:
  6049. if filename != '':
  6050. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6051. def on_file_openproject(self, checked=None):
  6052. """
  6053. File menu callback for opening a project.
  6054. :return: None
  6055. """
  6056. self.report_usage("on_file_openproject")
  6057. App.log.debug("on_file_openproject()")
  6058. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6059. try:
  6060. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6061. directory=self.get_last_folder(), filter=_filter_)
  6062. except TypeError:
  6063. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6064. # The Qt methods above will return a QString which can cause problems later.
  6065. # So far json.dump() will fail to serialize it.
  6066. # TODO: Improve the serialization methods and remove this fix.
  6067. filename = str(filename)
  6068. if filename == "":
  6069. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  6070. else:
  6071. # self.worker_task.emit({'fcn': self.open_project,
  6072. # 'params': [filename]})
  6073. # The above was failing because open_project() is not
  6074. # thread safe. The new_project()
  6075. self.open_project(filename)
  6076. def on_file_openconfig(self, checked=None):
  6077. """
  6078. File menu callback for opening a config file.
  6079. :return: None
  6080. """
  6081. self.report_usage("on_file_openconfig")
  6082. App.log.debug("on_file_openconfig()")
  6083. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6084. try:
  6085. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6086. directory=self.data_path, filter=_filter_)
  6087. except TypeError:
  6088. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6089. filter=_filter_)
  6090. if filename == "":
  6091. self.inform.emit(_("[WARNING_NOTCL] Open Config cancelled."))
  6092. else:
  6093. self.open_config_file(filename)
  6094. def on_file_exportsvg(self):
  6095. """
  6096. Callback for menu item File->Export SVG.
  6097. :return: None
  6098. """
  6099. self.report_usage("on_file_exportsvg")
  6100. App.log.debug("on_file_exportsvg()")
  6101. obj = self.collection.get_active()
  6102. if obj is None:
  6103. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6104. msg = _("Please Select a Geometry object to export")
  6105. msgbox = QtWidgets.QMessageBox()
  6106. msgbox.setInformativeText(msg)
  6107. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6108. msgbox.setDefaultButton(bt_ok)
  6109. msgbox.exec_()
  6110. return
  6111. # Check for more compatible types and add as required
  6112. if (not isinstance(obj, FlatCAMGeometry)
  6113. and not isinstance(obj, FlatCAMGerber)
  6114. and not isinstance(obj, FlatCAMCNCjob)
  6115. and not isinstance(obj, FlatCAMExcellon)):
  6116. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  6117. msgbox = QtWidgets.QMessageBox()
  6118. msgbox.setInformativeText(msg)
  6119. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6120. msgbox.setDefaultButton(bt_ok)
  6121. msgbox.exec_()
  6122. return
  6123. name = obj.options["name"]
  6124. _filter = "SVG File (*.svg);;All Files (*.*)"
  6125. try:
  6126. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6127. caption=_("Export SVG"),
  6128. directory=self.get_last_save_folder() + '/' + str(name),
  6129. filter=_filter)
  6130. except TypeError:
  6131. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6132. filename = str(filename)
  6133. if filename == "":
  6134. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  6135. return
  6136. else:
  6137. self.export_svg(name, filename)
  6138. if self.defaults["global_open_style"] is False:
  6139. self.file_opened.emit("SVG", filename)
  6140. self.file_saved.emit("SVG", filename)
  6141. def on_file_exportpng(self):
  6142. self.report_usage("on_file_exportpng")
  6143. App.log.debug("on_file_exportpng()")
  6144. self.date = str(datetime.today()).rpartition('.')[0]
  6145. self.date = ''.join(c for c in self.date if c not in ':-')
  6146. self.date = self.date.replace(' ', '_')
  6147. image = _screenshot()
  6148. data = np.asarray(image)
  6149. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6150. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  6151. return
  6152. filter_ = "PNG File (*.png);;All Files (*.*)"
  6153. try:
  6154. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6155. caption=_("Export PNG Image"),
  6156. directory=self.get_last_save_folder() + '/png_' + self.date,
  6157. filter=filter_)
  6158. except TypeError:
  6159. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6160. filename = str(filename)
  6161. if filename == "":
  6162. self.inform.emit(_("Export PNG cancelled."))
  6163. return
  6164. else:
  6165. write_png(filename, data)
  6166. if self.defaults["global_open_style"] is False:
  6167. self.file_opened.emit("png", filename)
  6168. self.file_saved.emit("png", filename)
  6169. def on_file_savegerber(self):
  6170. """
  6171. Callback for menu item File->Export Gerber.
  6172. :return: None
  6173. """
  6174. self.report_usage("on_file_savegerber")
  6175. App.log.debug("on_file_savegerber()")
  6176. obj = self.collection.get_active()
  6177. if obj is None:
  6178. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  6179. return
  6180. # Check for more compatible types and add as required
  6181. if not isinstance(obj, FlatCAMGerber):
  6182. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  6183. return
  6184. name = self.collection.get_active().options["name"]
  6185. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6186. try:
  6187. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6188. caption="Save Gerber source file",
  6189. directory=self.get_last_save_folder() + '/' + name,
  6190. filter=_filter)
  6191. except TypeError:
  6192. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6193. filename = str(filename)
  6194. if filename == "":
  6195. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  6196. return
  6197. else:
  6198. self.save_source_file(name, filename)
  6199. if self.defaults["global_open_style"] is False:
  6200. self.file_opened.emit("Gerber", filename)
  6201. self.file_saved.emit("Gerber", filename)
  6202. def on_file_saveexcellon(self):
  6203. """
  6204. Callback for menu item File->Export Gerber.
  6205. :return: None
  6206. """
  6207. self.report_usage("on_file_saveexcellon")
  6208. App.log.debug("on_file_saveexcellon()")
  6209. obj = self.collection.get_active()
  6210. if obj is None:
  6211. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  6212. return
  6213. # Check for more compatible types and add as required
  6214. if not isinstance(obj, FlatCAMExcellon):
  6215. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  6216. return
  6217. name = self.collection.get_active().options["name"]
  6218. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6219. try:
  6220. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6221. caption=_("Save Excellon source file"),
  6222. directory=self.get_last_save_folder() + '/' + name,
  6223. filter=_filter)
  6224. except TypeError:
  6225. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6226. filename = str(filename)
  6227. if filename == "":
  6228. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  6229. return
  6230. else:
  6231. self.save_source_file(name, filename)
  6232. if self.defaults["global_open_style"] is False:
  6233. self.file_opened.emit("Excellon", filename)
  6234. self.file_saved.emit("Excellon", filename)
  6235. def on_file_exportexcellon(self):
  6236. """
  6237. Callback for menu item File->Export->Excellon.
  6238. :return: None
  6239. """
  6240. self.report_usage("on_file_exportexcellon")
  6241. App.log.debug("on_file_exportexcellon()")
  6242. obj = self.collection.get_active()
  6243. if obj is None:
  6244. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  6245. return
  6246. # Check for more compatible types and add as required
  6247. if not isinstance(obj, FlatCAMExcellon):
  6248. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  6249. return
  6250. name = self.collection.get_active().options["name"]
  6251. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6252. try:
  6253. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6254. caption=_("Export Excellon"),
  6255. directory=self.get_last_save_folder() + '/' + name,
  6256. filter=_filter)
  6257. except TypeError:
  6258. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6259. filename = str(filename)
  6260. if filename == "":
  6261. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  6262. return
  6263. else:
  6264. self.export_excellon(name, filename)
  6265. if self.defaults["global_open_style"] is False:
  6266. self.file_opened.emit("Excellon", filename)
  6267. self.file_saved.emit("Excellon", filename)
  6268. def on_file_exportgerber(self):
  6269. """
  6270. Callback for menu item File->Export->Gerber.
  6271. :return: None
  6272. """
  6273. self.report_usage("on_file_exportgerber")
  6274. App.log.debug("on_file_exportgerber()")
  6275. obj = self.collection.get_active()
  6276. if obj is None:
  6277. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  6278. return
  6279. # Check for more compatible types and add as required
  6280. if not isinstance(obj, FlatCAMGerber):
  6281. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  6282. return
  6283. name = self.collection.get_active().options["name"]
  6284. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6285. try:
  6286. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6287. caption=_("Export Gerber"),
  6288. directory=self.get_last_save_folder() + '/' + name,
  6289. filter=_filter_)
  6290. except TypeError:
  6291. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6292. filename = str(filename)
  6293. if filename == "":
  6294. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  6295. return
  6296. else:
  6297. self.export_gerber(name, filename)
  6298. if self.defaults["global_open_style"] is False:
  6299. self.file_opened.emit("Gerber", filename)
  6300. self.file_saved.emit("Gerber", filename)
  6301. def on_file_exportdxf(self):
  6302. """
  6303. Callback for menu item File->Export DXF.
  6304. :return: None
  6305. """
  6306. self.report_usage("on_file_exportdxf")
  6307. App.log.debug("on_file_exportdxf()")
  6308. obj = self.collection.get_active()
  6309. if obj is None:
  6310. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6311. msg = _("Please Select a Geometry object to export")
  6312. msgbox = QtWidgets.QMessageBox()
  6313. msgbox.setInformativeText(msg)
  6314. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6315. msgbox.setDefaultButton(bt_ok)
  6316. msgbox.exec_()
  6317. return
  6318. # Check for more compatible types and add as required
  6319. if not isinstance(obj, FlatCAMGeometry):
  6320. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  6321. msgbox = QtWidgets.QMessageBox()
  6322. msgbox.setInformativeText(msg)
  6323. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6324. msgbox.setDefaultButton(bt_ok)
  6325. msgbox.exec_()
  6326. return
  6327. name = self.collection.get_active().options["name"]
  6328. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6329. try:
  6330. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6331. caption=_("Export DXF"),
  6332. directory=self.get_last_save_folder() + '/' + name,
  6333. filter=_filter_)
  6334. except TypeError:
  6335. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6336. filter=_filter_)
  6337. filename = str(filename)
  6338. if filename == "":
  6339. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  6340. return
  6341. else:
  6342. self.export_dxf(name, filename)
  6343. if self.defaults["global_open_style"] is False:
  6344. self.file_opened.emit("DXF", filename)
  6345. self.file_saved.emit("DXF", filename)
  6346. def on_file_importsvg(self, type_of_obj):
  6347. """
  6348. Callback for menu item File->Import SVG.
  6349. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6350. :type type_of_obj: str
  6351. :return: None
  6352. """
  6353. self.report_usage("on_file_importsvg")
  6354. App.log.debug("on_file_importsvg()")
  6355. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6356. try:
  6357. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6358. directory=self.get_last_folder(), filter=_filter_)
  6359. except TypeError:
  6360. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6361. filter=_filter_)
  6362. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6363. type_of_obj = "geometry"
  6364. filenames = [str(filename) for filename in filenames]
  6365. if len(filenames) == 0:
  6366. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  6367. else:
  6368. for filename in filenames:
  6369. if filename != '':
  6370. self.worker_task.emit({'fcn': self.import_svg,
  6371. 'params': [filename, type_of_obj]})
  6372. def on_file_importdxf(self, type_of_obj):
  6373. """
  6374. Callback for menu item File->Import DXF.
  6375. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6376. :type type_of_obj: str
  6377. :return: None
  6378. """
  6379. self.report_usage("on_file_importdxf")
  6380. App.log.debug("on_file_importdxf()")
  6381. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6382. try:
  6383. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6384. directory=self.get_last_folder(),
  6385. filter=_filter_)
  6386. except TypeError:
  6387. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6388. filter=_filter_)
  6389. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6390. type_of_obj = "geometry"
  6391. filenames = [str(filename) for filename in filenames]
  6392. if len(filenames) == 0:
  6393. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  6394. else:
  6395. for filename in filenames:
  6396. if filename != '':
  6397. self.worker_task.emit({'fcn': self.import_dxf,
  6398. 'params': [filename, type_of_obj]})
  6399. # ###############################################################################################################
  6400. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6401. # ###############################################################################################################
  6402. def init_code_editor(self, name):
  6403. # Signals section
  6404. # Disconnect the old signals
  6405. self.ui.buttonOpen.clicked.disconnect()
  6406. self.ui.buttonSave.clicked.disconnect()
  6407. # add the tab if it was closed
  6408. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  6409. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6410. # delete the absolute and relative position and messages in the infobar
  6411. self.ui.position_label.setText("")
  6412. self.ui.rel_position_label.setText("")
  6413. # first clear previous text in text editor (if any)
  6414. self.ui.code_editor.clear()
  6415. self.ui.code_editor.setReadOnly(False)
  6416. self.toggle_codeeditor = True
  6417. self.ui.code_editor.completer_enable = False
  6418. # Switch plot_area to CNCJob tab
  6419. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6420. def on_view_source(self):
  6421. try:
  6422. obj = self.collection.get_active()
  6423. except:
  6424. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  6425. return 'fail'
  6426. # then append the text from GCode to the text editor
  6427. try:
  6428. file = StringIO(obj.source_file)
  6429. except AttributeError:
  6430. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  6431. return 'fail'
  6432. if obj.kind == 'gerber':
  6433. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6434. elif obj.kind == 'excellon':
  6435. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6436. self.init_code_editor(name=_("Source Editor"))
  6437. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6438. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6439. try:
  6440. for line in file:
  6441. proc_line = str(line).strip('\n')
  6442. self.ui.code_editor.append(proc_line)
  6443. except Exception as e:
  6444. log.debug('App.on_view_source() -->%s' % str(e))
  6445. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  6446. return
  6447. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6448. self.handleTextChanged()
  6449. self.ui.show()
  6450. def on_toggle_code_editor(self):
  6451. self.report_usage("on_toggle_code_editor()")
  6452. if self.toggle_codeeditor is False:
  6453. self.init_code_editor(name=_("Code Editor"))
  6454. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6455. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6456. else:
  6457. for idx in range(self.ui.plot_tab_area.count()):
  6458. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6459. self.ui.plot_tab_area.closeTab(idx)
  6460. break
  6461. self.toggle_codeeditor = False
  6462. def on_filenewscript(self):
  6463. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6464. self.init_code_editor(name=_("Script Editor"))
  6465. self.ui.code_editor.completer_enable = True
  6466. self.ui.code_editor.append(_(
  6467. "#\n"
  6468. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6469. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6470. "#\n\n"
  6471. "# FlatCAM commands list:\n"
  6472. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  6473. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  6474. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  6475. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  6476. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  6477. "# WriteGCode\n"
  6478. "#\n\n"
  6479. ))
  6480. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6481. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6482. self.handleTextChanged()
  6483. self.ui.code_editor.show()
  6484. def on_fileopenscript(self):
  6485. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6486. try:
  6487. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6488. directory=self.get_last_folder(), filter=_filter_)
  6489. except TypeError:
  6490. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6491. # The Qt methods above will return a QString which can cause problems later.
  6492. # So far json.dump() will fail to serialize it.
  6493. # TODO: Improve the serialization methods and remove this fix.
  6494. filename = str(filename)
  6495. if filename == "":
  6496. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  6497. else:
  6498. self.on_filenewscript()
  6499. try:
  6500. with open(filename, "r") as opened_script:
  6501. try:
  6502. for line in opened_script:
  6503. proc_line = str(line).strip('\n')
  6504. self.ui.code_editor.append(proc_line)
  6505. except Exception as e:
  6506. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6507. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  6508. return
  6509. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6510. self.handleTextChanged()
  6511. self.ui.show()
  6512. except Exception as e:
  6513. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6514. def on_filerunscript(self, name=None):
  6515. """
  6516. File menu callback for loading and running a TCL script.
  6517. :return: None
  6518. """
  6519. self.report_usage("on_filerunscript")
  6520. App.log.debug("on_file_runscript()")
  6521. if name:
  6522. filename = name
  6523. else:
  6524. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6525. try:
  6526. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6527. directory=self.get_last_folder(), filter=_filter_)
  6528. except TypeError:
  6529. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6530. # The Qt methods above will return a QString which can cause problems later.
  6531. # So far json.dump() will fail to serialize it.
  6532. # TODO: Improve the serialization methods and remove this fix.
  6533. filename = str(filename)
  6534. if filename == "":
  6535. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  6536. else:
  6537. try:
  6538. with open(filename, "r") as tcl_script:
  6539. cmd_line_shellfile_content = tcl_script.read()
  6540. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6541. except Exception as e:
  6542. log.debug("App.on_filerunscript() -> %s" % str(e))
  6543. sys.exit(2)
  6544. def on_file_saveproject(self):
  6545. """
  6546. Callback for menu item File->Save Project. Saves the project to
  6547. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6548. if set to None. The project is saved by calling ``self.save_project()``.
  6549. :return: None
  6550. """
  6551. self.report_usage("on_file_saveproject")
  6552. if self.project_filename is None:
  6553. self.on_file_saveprojectas()
  6554. else:
  6555. self.worker_task.emit({'fcn': self.save_project,
  6556. 'params': [self.project_filename]})
  6557. if self.defaults["global_open_style"] is False:
  6558. self.file_opened.emit("project", self.project_filename)
  6559. self.file_saved.emit("project", self.project_filename)
  6560. self.set_ui_title(name=self.project_filename)
  6561. self.should_we_save = False
  6562. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6563. """
  6564. Callback for menu item File->Save Project As... Opens a file
  6565. chooser and saves the project to the given file via
  6566. ``self.save_project()``.
  6567. :param make_copy if to be create a copy of the project; boolean
  6568. :param use_thread: if to be run in a separate thread; boolean
  6569. :param quit_action: if to be followed by quiting the application; boolean
  6570. :return: None
  6571. """
  6572. self.report_usage("on_file_saveprojectas")
  6573. self.date = str(datetime.today()).rpartition('.')[0]
  6574. self.date = ''.join(c for c in self.date if c not in ':-')
  6575. self.date = self.date.replace(' ', '_')
  6576. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6577. try:
  6578. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6579. caption=_("Save Project As ..."),
  6580. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6581. filter=filter_)
  6582. except TypeError:
  6583. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6584. filename = str(filename)
  6585. if filename == '':
  6586. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  6587. return
  6588. try:
  6589. f = open(filename, 'r')
  6590. f.close()
  6591. except IOError:
  6592. pass
  6593. if use_thread is True:
  6594. self.worker_task.emit({'fcn': self.save_project,
  6595. 'params': [filename, quit_action]})
  6596. else:
  6597. self.save_project(filename, quit_action)
  6598. # self.save_project(filename)
  6599. if self.defaults["global_open_style"] is False:
  6600. self.file_opened.emit("project", filename)
  6601. self.file_saved.emit("project", filename)
  6602. if not make_copy:
  6603. self.project_filename = filename
  6604. self.set_ui_title(name=self.project_filename)
  6605. self.should_we_save = False
  6606. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6607. """
  6608. Exports a Geometry Object to an SVG file.
  6609. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6610. :param filename: Path to the SVG file to save to.
  6611. :param scale_factor: factor by which to change/scale the thickness of the features
  6612. :return:
  6613. """
  6614. self.report_usage("export_svg()")
  6615. if filename is None:
  6616. filename = self.defaults["global_last_save_folder"]
  6617. self.log.debug("export_svg()")
  6618. try:
  6619. obj = self.collection.get_by_name(str(obj_name))
  6620. except:
  6621. # TODO: The return behavior has not been established... should raise exception?
  6622. return "Could not retrieve object: %s" % obj_name
  6623. with self.proc_container.new(_("Exporting SVG")) as proc:
  6624. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6625. # Determine bounding area for svg export
  6626. bounds = obj.bounds()
  6627. size = obj.size()
  6628. # Convert everything to strings for use in the xml doc
  6629. svgwidth = str(size[0])
  6630. svgheight = str(size[1])
  6631. minx = str(bounds[0])
  6632. miny = str(bounds[1] - size[1])
  6633. uom = obj.units.lower()
  6634. # Add a SVG Header and footer to the svg output from shapely
  6635. # The transform flips the Y Axis so that everything renders
  6636. # properly within svg apps such as inkscape
  6637. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6638. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6639. svg_header += 'width="' + svgwidth + uom + '" '
  6640. svg_header += 'height="' + svgheight + uom + '" '
  6641. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6642. svg_header += '<g transform="scale(1,-1)">'
  6643. svg_footer = '</g> </svg>'
  6644. svg_elem = svg_header + exported_svg + svg_footer
  6645. # Parse the xml through a xml parser just to add line feeds
  6646. # and to make it look more pretty for the output
  6647. svgcode = parse_xml_string(svg_elem)
  6648. try:
  6649. with open(filename, 'w') as fp:
  6650. fp.write(svgcode.toprettyxml())
  6651. except PermissionError:
  6652. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6653. "Most likely another app is holding the file open and not accessible."))
  6654. return 'fail'
  6655. if self.defaults["global_open_style"] is False:
  6656. self.file_opened.emit("SVG", filename)
  6657. self.file_saved.emit("SVG", filename)
  6658. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6659. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6660. """
  6661. Exports a Geometry Object to an SVG file in negative.
  6662. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6663. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6664. :param filename: Path to the SVG file to save to.
  6665. :param boundary: thickness of a black border to surround all the features
  6666. :param scale_factor: factor by which to change/scale the thickness of the features
  6667. :param use_thread: if to be run in a separate thread; boolean
  6668. :return:
  6669. """
  6670. self.report_usage("export_negative()")
  6671. if filename is None:
  6672. filename = self.defaults["global_last_save_folder"]
  6673. self.log.debug("export_svg() negative")
  6674. try:
  6675. obj = self.collection.get_by_name(str(obj_name))
  6676. except:
  6677. # TODO: The return behavior has not been established... should raise exception?
  6678. return "Could not retrieve object: %s" % obj_name
  6679. try:
  6680. box = self.collection.get_by_name(str(box_name))
  6681. except:
  6682. # TODO: The return behavior has not been established... should raise exception?
  6683. return "Could not retrieve object: %s" % box_name
  6684. if box is None:
  6685. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6686. box = obj
  6687. def make_negative_film():
  6688. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6689. self.progress.emit(40)
  6690. # Determine bounding area for svg export
  6691. bounds = box.bounds()
  6692. size = box.size()
  6693. uom = obj.units.lower()
  6694. # Convert everything to strings for use in the xml doc
  6695. svgwidth = str(size[0] + (2 * boundary))
  6696. svgheight = str(size[1] + (2 * boundary))
  6697. minx = str(bounds[0] - boundary)
  6698. miny = str(bounds[1] + boundary + size[1])
  6699. miny_rect = str(bounds[1] - boundary)
  6700. # Add a SVG Header and footer to the svg output from shapely
  6701. # The transform flips the Y Axis so that everything renders
  6702. # properly within svg apps such as inkscape
  6703. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6704. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6705. svg_header += 'width="' + svgwidth + uom + '" '
  6706. svg_header += 'height="' + svgheight + uom + '" '
  6707. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6708. svg_header += '>'
  6709. svg_header += '<g transform="scale(1,-1)">'
  6710. svg_footer = '</g> </svg>'
  6711. self.progress.emit(60)
  6712. # Change the attributes of the exported SVG
  6713. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6714. # We set opacity to maximum
  6715. # We set the color to WHITE
  6716. root = ET.fromstring(exported_svg)
  6717. for child in root:
  6718. child.set('fill', '#FFFFFF')
  6719. child.set('opacity', '1.0')
  6720. child.set('stroke', '#FFFFFF')
  6721. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6722. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6723. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6724. first_svg_elem_tag = 'rect'
  6725. first_svg_elem_attribs = {
  6726. 'x': minx,
  6727. 'y': miny_rect,
  6728. 'width': svgwidth,
  6729. 'height': svgheight,
  6730. 'id': 'neg_rect',
  6731. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6732. }
  6733. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6734. exported_svg = ET.tostring(root)
  6735. svg_elem = svg_header + str(exported_svg) + svg_footer
  6736. self.progress.emit(80)
  6737. # Parse the xml through a xml parser just to add line feeds
  6738. # and to make it look more pretty for the output
  6739. doc = parse_xml_string(svg_elem)
  6740. try:
  6741. with open(filename, 'w') as fp:
  6742. fp.write(doc.toprettyxml())
  6743. except PermissionError:
  6744. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6745. "Most likely another app is holding the file open and not accessible."))
  6746. return 'fail'
  6747. self.progress.emit(100)
  6748. if self.defaults["global_open_style"] is False:
  6749. self.file_opened.emit("SVG", filename)
  6750. self.file_saved.emit("SVG", filename)
  6751. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6752. if use_thread is True:
  6753. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6754. def job_thread_film(app_obj):
  6755. try:
  6756. make_negative_film()
  6757. except Exception as e:
  6758. proc.done()
  6759. return
  6760. proc.done()
  6761. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6762. else:
  6763. make_negative_film()
  6764. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6765. """
  6766. Exports a Geometry Object to an SVG file in positive black.
  6767. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6768. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6769. :param filename: Path to the SVG file to save to.
  6770. :param scale_factor: factor by which to change/scale the thickness of the features
  6771. :param use_thread: if to be run in a separate thread; boolean
  6772. :return:
  6773. """
  6774. self.report_usage("export_svg_black()")
  6775. if filename is None:
  6776. filename = self.defaults["global_last_save_folder"]
  6777. self.log.debug("export_svg() black")
  6778. try:
  6779. obj = self.collection.get_by_name(str(obj_name))
  6780. except:
  6781. # TODO: The return behavior has not been established... should raise exception?
  6782. return "Could not retrieve object: %s" % obj_name
  6783. try:
  6784. box = self.collection.get_by_name(str(box_name))
  6785. except:
  6786. # TODO: The return behavior has not been established... should raise exception?
  6787. return "Could not retrieve object: %s" % box_name
  6788. if box is None:
  6789. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6790. box = obj
  6791. def make_black_film():
  6792. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6793. self.progress.emit(40)
  6794. # Change the attributes of the exported SVG
  6795. # We don't need stroke-width
  6796. # We set opacity to maximum
  6797. # We set the colour to WHITE
  6798. root = ET.fromstring(exported_svg)
  6799. for child in root:
  6800. child.set('fill', '#000000')
  6801. child.set('opacity', '1.0')
  6802. child.set('stroke', '#000000')
  6803. exported_svg = ET.tostring(root)
  6804. # Determine bounding area for svg export
  6805. bounds = box.bounds()
  6806. size = box.size()
  6807. # This contain the measure units
  6808. uom = obj.units.lower()
  6809. # Define a boundary around SVG of about 1.0mm (~39mils)
  6810. if uom in "mm":
  6811. boundary = 1.0
  6812. else:
  6813. boundary = 0.0393701
  6814. self.progress.emit(80)
  6815. # Convert everything to strings for use in the xml doc
  6816. svgwidth = str(size[0] + (2 * boundary))
  6817. svgheight = str(size[1] + (2 * boundary))
  6818. minx = str(bounds[0] - boundary)
  6819. miny = str(bounds[1] + boundary + size[1])
  6820. self.log.debug(minx)
  6821. self.log.debug(miny)
  6822. # Add a SVG Header and footer to the svg output from shapely
  6823. # The transform flips the Y Axis so that everything renders
  6824. # properly within svg apps such as inkscape
  6825. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6826. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6827. svg_header += 'width="' + svgwidth + uom + '" '
  6828. svg_header += 'height="' + svgheight + uom + '" '
  6829. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6830. svg_header += '>'
  6831. svg_header += '<g transform="scale(1,-1)">'
  6832. svg_footer = '</g> </svg>'
  6833. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  6834. self.progress.emit(90)
  6835. # Parse the xml through a xml parser just to add line feeds
  6836. # and to make it look more pretty for the output
  6837. doc = parse_xml_string(svg_elem)
  6838. try:
  6839. with open(filename, 'w') as fp:
  6840. fp.write(doc.toprettyxml())
  6841. except PermissionError:
  6842. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6843. "Most likely another app is holding the file open and not accessible."))
  6844. return 'fail'
  6845. self.progress.emit(100)
  6846. if self.defaults["global_open_style"] is False:
  6847. self.file_opened.emit("SVG", filename)
  6848. self.file_saved.emit("SVG", filename)
  6849. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6850. if use_thread is True:
  6851. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6852. def job_thread_film(app_obj):
  6853. try:
  6854. make_black_film()
  6855. except Exception as e:
  6856. proc.done()
  6857. return
  6858. proc.done()
  6859. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6860. else:
  6861. make_black_film()
  6862. def save_source_file(self, obj_name, filename, use_thread=True):
  6863. """
  6864. Exports a FlatCAM Object to an Gerber/Excellon file.
  6865. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6866. :param filename: Path to the Gerber file to save to.
  6867. :param use_thread: if to be run in a separate thread
  6868. :return:
  6869. """
  6870. self.report_usage("save source file()")
  6871. if filename is None:
  6872. filename = self.defaults["global_last_save_folder"]
  6873. self.log.debug("save source file()")
  6874. obj = self.collection.get_by_name(obj_name)
  6875. file_string = StringIO(obj.source_file)
  6876. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6877. try:
  6878. with open(filename, 'w') as file:
  6879. file.writelines('G04*\n')
  6880. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6881. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6882. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6883. file.writelines('G04 Created on : %s*\n' % time_string)
  6884. for line in file_string:
  6885. file.writelines(line)
  6886. except PermissionError:
  6887. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6888. "Most likely another app is holding the file open and not accessible."))
  6889. return 'fail'
  6890. def export_excellon(self, obj_name, filename, use_thread=True):
  6891. """
  6892. Exports a Excellon Object to an Excellon file.
  6893. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6894. :param filename: Path to the Excellon file to save to.
  6895. :param use_thread: if to be run in a separate thread
  6896. :return:
  6897. """
  6898. self.report_usage("export_excellon()")
  6899. if filename is None:
  6900. filename = self.defaults["global_last_save_folder"]
  6901. self.log.debug("export_excellon()")
  6902. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6903. self.defaults["excellon_exp_decimals"]
  6904. )
  6905. units = ''
  6906. try:
  6907. obj = self.collection.get_by_name(str(obj_name))
  6908. except:
  6909. # TODO: The return behavior has not been established... should raise exception?
  6910. return "Could not retrieve object: %s" % obj_name
  6911. # updated units
  6912. eunits = self.defaults["excellon_exp_units"]
  6913. ewhole = self.defaults["excellon_exp_integer"]
  6914. efract = self.defaults["excellon_exp_decimals"]
  6915. ezeros = self.defaults["excellon_exp_zeros"]
  6916. eformat = self.defaults["excellon_exp_format"]
  6917. slot_type = self.defaults["excellon_exp_slot_type"]
  6918. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6919. if fc_units == 'MM':
  6920. factor = 1 if eunits == 'METRIC' else 0.03937
  6921. else:
  6922. factor = 25.4 if eunits == 'METRIC' else 1
  6923. def make_excellon():
  6924. try:
  6925. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6926. header = 'M48\n'
  6927. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6928. (str(self.version), str(self.version_date))
  6929. header += ';Filename: %s' % str(obj_name) + '\n'
  6930. header += ';Created on : %s' % time_str + '\n'
  6931. if eformat == 'dec':
  6932. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6933. header += eunits + '\n'
  6934. for tool in obj.tools:
  6935. if eunits == 'METRIC':
  6936. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6937. tool=str(tool),
  6938. dec=2)
  6939. else:
  6940. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6941. tool=str(tool),
  6942. dec=4)
  6943. else:
  6944. if ezeros == 'LZ':
  6945. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6946. form='ndec', e_zeros='LZ', factor=factor,
  6947. slot_type=slot_type)
  6948. header += '%s,%s\n' % (eunits, 'LZ')
  6949. header += format_exc
  6950. for tool in obj.tools:
  6951. if eunits == 'METRIC':
  6952. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6953. tool=str(tool),
  6954. dec=2)
  6955. else:
  6956. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6957. tool=str(tool),
  6958. dec=4)
  6959. else:
  6960. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6961. form='ndec', e_zeros='TZ', factor=factor,
  6962. slot_type=slot_type)
  6963. header += '%s,%s\n' % (eunits, 'TZ')
  6964. header += format_exc
  6965. for tool in obj.tools:
  6966. if eunits == 'METRIC':
  6967. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6968. tool=str(tool),
  6969. dec=2)
  6970. else:
  6971. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6972. tool=str(tool),
  6973. dec=4)
  6974. header += '%\n'
  6975. footer = 'M30\n'
  6976. exported_excellon = header
  6977. exported_excellon += excellon_code
  6978. exported_excellon += footer
  6979. try:
  6980. with open(filename, 'w') as fp:
  6981. fp.write(exported_excellon)
  6982. except PermissionError:
  6983. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6984. "Most likely another app is holding the file open and not accessible."))
  6985. return 'fail'
  6986. if self.defaults["global_open_style"] is False:
  6987. self.file_opened.emit("Excellon", filename)
  6988. self.file_saved.emit("Excellon", filename)
  6989. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  6990. except Exception as e:
  6991. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6992. return 'fail'
  6993. if use_thread is True:
  6994. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6995. def job_thread_exc(app_obj):
  6996. ret = make_excellon()
  6997. if ret == 'fail':
  6998. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6999. return
  7000. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7001. else:
  7002. ret = make_excellon()
  7003. if ret == 'fail':
  7004. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  7005. return
  7006. def export_gerber(self, obj_name, filename, use_thread=True):
  7007. """
  7008. Exports a Gerber Object to an Gerber file.
  7009. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7010. :param filename: Path to the Gerber file to save to.
  7011. :param use_thread: if to be run in a separate thread
  7012. :return:
  7013. """
  7014. self.report_usage("export_gerber()")
  7015. if filename is None:
  7016. filename = self.defaults["global_last_save_folder"]
  7017. self.log.debug("export_gerber()")
  7018. try:
  7019. obj = self.collection.get_by_name(str(obj_name))
  7020. except:
  7021. # TODO: The return behavior has not been established... should raise exception?
  7022. return "Could not retrieve object: %s" % obj_name
  7023. # updated units
  7024. gunits = self.defaults["gerber_exp_units"]
  7025. gwhole = self.defaults["gerber_exp_integer"]
  7026. gfract = self.defaults["gerber_exp_decimals"]
  7027. gzeros = self.defaults["gerber_exp_zeros"]
  7028. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7029. if fc_units == 'MM':
  7030. factor = 1 if gunits == 'MM' else 0.03937
  7031. else:
  7032. factor = 25.4 if gunits == 'MM' else 1
  7033. def make_gerber():
  7034. try:
  7035. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7036. header = 'G04*\n'
  7037. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7038. (str(self.version), str(self.version_date))
  7039. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7040. header += 'G04 Created on : %s*' % time_str + '\n'
  7041. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7042. header += "%MO{units}*%\n".format(units=gunits)
  7043. for apid in obj.apertures:
  7044. if obj.apertures[apid]['type'] == 'C':
  7045. header += "%ADD{apid}{type},{size}*%\n".format(
  7046. apid=str(apid),
  7047. type='C',
  7048. size=(factor * obj.apertures[apid]['size'])
  7049. )
  7050. elif obj.apertures[apid]['type'] == 'R':
  7051. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7052. apid=str(apid),
  7053. type='R',
  7054. width=(factor * obj.apertures[apid]['width']),
  7055. height=(factor * obj.apertures[apid]['height'])
  7056. )
  7057. elif obj.apertures[apid]['type'] == 'O':
  7058. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7059. apid=str(apid),
  7060. type='O',
  7061. width=(factor * obj.apertures[apid]['width']),
  7062. height=(factor * obj.apertures[apid]['height'])
  7063. )
  7064. header += '\n'
  7065. # obsolete units but some software may need it
  7066. if gunits == 'IN':
  7067. header += 'G70*\n'
  7068. else:
  7069. header += 'G71*\n'
  7070. # Absolute Mode
  7071. header += 'G90*\n'
  7072. header += 'G01*\n'
  7073. # positive polarity
  7074. header += '%LPD*%\n'
  7075. footer = 'M02*\n'
  7076. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7077. exported_gerber = header
  7078. exported_gerber += gerber_code
  7079. exported_gerber += footer
  7080. try:
  7081. with open(filename, 'w') as fp:
  7082. fp.write(exported_gerber)
  7083. except PermissionError:
  7084. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  7085. "Most likely another app is holding the file open and not accessible."))
  7086. return 'fail'
  7087. if self.defaults["global_open_style"] is False:
  7088. self.file_opened.emit("Gerber", filename)
  7089. self.file_saved.emit("Gerber", filename)
  7090. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  7091. except Exception as e:
  7092. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7093. return 'fail'
  7094. if use_thread is True:
  7095. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7096. def job_thread_exc(app_obj):
  7097. ret = make_gerber()
  7098. if ret == 'fail':
  7099. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  7100. return
  7101. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7102. else:
  7103. ret = make_gerber()
  7104. if ret == 'fail':
  7105. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  7106. return
  7107. def export_dxf(self, obj_name, filename, use_thread=True):
  7108. """
  7109. Exports a Geometry Object to an DXF file.
  7110. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7111. :param filename: Path to the DXF file to save to.
  7112. :param use_thread: if to be run in a separate thread
  7113. :return:
  7114. """
  7115. self.report_usage("export_dxf()")
  7116. if filename is None:
  7117. filename = self.defaults["global_last_save_folder"]
  7118. self.log.debug("export_dxf()")
  7119. format_exc = ''
  7120. units = ''
  7121. try:
  7122. obj = self.collection.get_by_name(str(obj_name))
  7123. except:
  7124. # TODO: The return behavior has not been established... should raise exception?
  7125. return "Could not retrieve object: %s" % obj_name
  7126. # updated units
  7127. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7128. if units == 'IN' or units == 'INCH':
  7129. units = 'INCH'
  7130. elif units == 'MM' or units == 'METIRC':
  7131. units ='METRIC'
  7132. def make_dxf():
  7133. try:
  7134. dxf_code = obj.export_dxf()
  7135. dxf_code.saveas(filename)
  7136. if self.defaults["global_open_style"] is False:
  7137. self.file_opened.emit("DXF", filename)
  7138. self.file_saved.emit("DXF", filename)
  7139. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  7140. except:
  7141. return 'fail'
  7142. if use_thread is True:
  7143. with self.proc_container.new(_("Exporting DXF")) as proc:
  7144. def job_thread_exc(app_obj):
  7145. ret = make_dxf()
  7146. if ret == 'fail':
  7147. app_obj.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  7148. return
  7149. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7150. else:
  7151. ret = make_dxf()
  7152. if ret == 'fail':
  7153. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  7154. return
  7155. def import_svg(self, filename, geo_type='geometry', outname=None):
  7156. """
  7157. Adds a new Geometry Object to the projects and populates
  7158. it with shapes extracted from the SVG file.
  7159. :param filename: Path to the SVG file.
  7160. :param outname:
  7161. :return:
  7162. """
  7163. self.report_usage("import_svg()")
  7164. obj_type = ""
  7165. if geo_type is None or geo_type == "geometry":
  7166. obj_type = "geometry"
  7167. elif geo_type == "gerber":
  7168. obj_type = geo_type
  7169. else:
  7170. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  7171. "Only Geometry and Gerber are supported"))
  7172. return
  7173. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7174. def obj_init(geo_obj, app_obj):
  7175. geo_obj.import_svg(filename, obj_type, units=units)
  7176. geo_obj.multigeo = False
  7177. with self.proc_container.new(_("Importing SVG")) as proc:
  7178. # Object name
  7179. name = outname or filename.split('/')[-1].split('\\')[-1]
  7180. self.new_object(obj_type, name, obj_init, autoselected=False)
  7181. self.progress.emit(20)
  7182. # Register recent file
  7183. self.file_opened.emit("svg", filename)
  7184. # GUI feedback
  7185. self.inform.emit(_("[success] Opened: %s") % filename)
  7186. self.progress.emit(100)
  7187. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7188. """
  7189. Adds a new Geometry Object to the projects and populates
  7190. it with shapes extracted from the DXF file.
  7191. :param filename: Path to the DXF file.
  7192. :param outname:
  7193. :type putname: str
  7194. :return:
  7195. """
  7196. self.report_usage("import_dxf()")
  7197. obj_type = ""
  7198. if geo_type is None or geo_type == "geometry":
  7199. obj_type = "geometry"
  7200. elif geo_type == "gerber":
  7201. obj_type = geo_type
  7202. else:
  7203. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  7204. "Only Geometry and Gerber are supported"))
  7205. return
  7206. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7207. def obj_init(geo_obj, app_obj):
  7208. geo_obj.import_dxf(filename, obj_type, units=units)
  7209. geo_obj.multigeo = False
  7210. with self.proc_container.new(_("Importing DXF")) as proc:
  7211. # Object name
  7212. name = outname or filename.split('/')[-1].split('\\')[-1]
  7213. self.new_object(obj_type, name, obj_init, autoselected=False)
  7214. self.progress.emit(20)
  7215. # Register recent file
  7216. self.file_opened.emit("dxf", filename)
  7217. # GUI feedback
  7218. self.inform.emit(_("[success] Opened: %s") % filename)
  7219. self.progress.emit(100)
  7220. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7221. """
  7222. Adds a new Geometry Object to the projects and populates
  7223. it with shapes extracted from the SVG file.
  7224. :param filename: Path to the SVG file.
  7225. :param o_type: type of FlatCAM objeect
  7226. :param dpi: dot per inch
  7227. :param mode: black or color
  7228. :param mask: dictate the level of detail
  7229. :param outname: name for the resulting file
  7230. :return:
  7231. """
  7232. self.report_usage("import_image()")
  7233. if o_type is None or o_type == "geometry":
  7234. obj_type = "geometry"
  7235. elif o_type == "gerber":
  7236. obj_type = o_type
  7237. else:
  7238. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  7239. "Only Geometry and Gerber are supported"))
  7240. return
  7241. def obj_init(geo_obj, app_obj):
  7242. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7243. geo_obj.multigeo = False
  7244. with self.proc_container.new(_("Importing Image")) as proc:
  7245. # Object name
  7246. name = outname or filename.split('/')[-1].split('\\')[-1]
  7247. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7248. self.new_object(obj_type, name, obj_init)
  7249. self.progress.emit(20)
  7250. # Register recent file
  7251. self.file_opened.emit("image", filename)
  7252. # GUI feedback
  7253. self.inform.emit(_("[success] Opened: %s") % filename)
  7254. self.progress.emit(100)
  7255. def open_gerber(self, filename, outname=None):
  7256. """
  7257. Opens a Gerber file, parses it and creates a new object for
  7258. it in the program. Thread-safe.
  7259. :param outname: Name of the resulting object. None causes the
  7260. name to be that of the file.
  7261. :param filename: Gerber file filename
  7262. :type filename: str
  7263. :param follow: If true, the parser will not create polygons, just lines
  7264. following the gerber path.
  7265. :type follow: bool
  7266. :return: None
  7267. """
  7268. # How the object should be initialized
  7269. def obj_init(gerber_obj, app_obj):
  7270. assert isinstance(gerber_obj, FlatCAMGerber), \
  7271. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7272. # Opening the file happens here
  7273. self.progress.emit(30)
  7274. try:
  7275. gerber_obj.parse_file(filename)
  7276. except IOError:
  7277. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  7278. app_obj.progress.emit(0)
  7279. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  7280. return "fail"
  7281. except ParseError as err:
  7282. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  7283. error=str(err)))
  7284. app_obj.progress.emit(0)
  7285. self.log.error(str(err))
  7286. return "fail"
  7287. except Exception as e:
  7288. log.debug("App.open_gerber() --> %s" % str(e))
  7289. msg = _("[ERROR] An internal error has occurred. See shell.\n")
  7290. msg += traceback.format_exc()
  7291. app_obj.inform.emit(msg)
  7292. return "fail"
  7293. if gerber_obj.is_empty():
  7294. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7295. # self.collection.set_active(gerber_obj.options["name"])
  7296. # self.collection.delete_active()
  7297. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  7298. return "fail"
  7299. # Further parsing
  7300. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7301. App.log.debug("open_gerber()")
  7302. with self.proc_container.new(_("Opening Gerber")) as proc:
  7303. self.progress.emit(10)
  7304. # Object name
  7305. name = outname or filename.split('/')[-1].split('\\')[-1]
  7306. # # ## Object creation # ##
  7307. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7308. if ret == 'fail':
  7309. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  7310. return
  7311. # Register recent file
  7312. self.file_opened.emit("gerber", filename)
  7313. self.progress.emit(100)
  7314. # GUI feedback
  7315. self.inform.emit(_("[success] Opened: %s") % filename)
  7316. def open_excellon(self, filename, outname=None):
  7317. """
  7318. Opens an Excellon file, parses it and creates a new object for
  7319. it in the program. Thread-safe.
  7320. :param outname: Name of the resulting object. None causes the
  7321. name to be that of the file.
  7322. :param filename: Excellon file filename
  7323. :type filename: str
  7324. :return: None
  7325. """
  7326. App.log.debug("open_excellon()")
  7327. # How the object should be initialized
  7328. def obj_init(excellon_obj, app_obj):
  7329. # self.progress.emit(20)
  7330. try:
  7331. ret = excellon_obj.parse_file(filename=filename)
  7332. if ret == "fail":
  7333. log.debug("Excellon parsing failed.")
  7334. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  7335. return "fail"
  7336. except IOError:
  7337. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  7338. log.debug("Could not open Excellon object.")
  7339. self.progress.emit(0) # TODO: self and app_bjj mixed
  7340. return "fail"
  7341. except:
  7342. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  7343. msg += traceback.format_exc()
  7344. app_obj.inform.emit(msg)
  7345. return "fail"
  7346. ret = excellon_obj.create_geometry()
  7347. if ret == 'fail':
  7348. log.debug("Could not create geometry for Excellon object.")
  7349. return "fail"
  7350. for tool in excellon_obj.tools:
  7351. if excellon_obj.tools[tool]['solid_geometry']:
  7352. return
  7353. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  7354. return "fail"
  7355. with self.proc_container.new(_("Opening Excellon.")):
  7356. # Object name
  7357. name = outname or filename.split('/')[-1].split('\\')[-1]
  7358. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  7359. if ret_val == 'fail':
  7360. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  7361. return
  7362. # Register recent file
  7363. self.file_opened.emit("excellon", filename)
  7364. # GUI feedback
  7365. self.inform.emit(_("[success] Opened: %s") % filename)
  7366. def open_gcode(self, filename, outname=None):
  7367. """
  7368. Opens a G-gcode file, parses it and creates a new object for
  7369. it in the program. Thread-safe.
  7370. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7371. :param filename: G-code file filename
  7372. :type filename: str
  7373. :return: None
  7374. """
  7375. App.log.debug("open_gcode()")
  7376. # How the object should be initialized
  7377. def obj_init(job_obj, app_obj_):
  7378. """
  7379. :param job_obj: the resulting object
  7380. :type app_obj_: App
  7381. """
  7382. assert isinstance(app_obj_, App), \
  7383. "Initializer expected App, got %s" % type(app_obj_)
  7384. self.progress.emit(10)
  7385. try:
  7386. f = open(filename)
  7387. gcode = f.read()
  7388. f.close()
  7389. except IOError:
  7390. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  7391. self.progress.emit(0)
  7392. return "fail"
  7393. job_obj.gcode = gcode
  7394. self.progress.emit(20)
  7395. ret = job_obj.gcode_parse()
  7396. if ret == "fail":
  7397. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  7398. return "fail"
  7399. self.progress.emit(60)
  7400. job_obj.create_geometry()
  7401. with self.proc_container.new(_("Opening G-Code.")):
  7402. # Object name
  7403. name = outname or filename.split('/')[-1].split('\\')[-1]
  7404. # New object creation and file processing
  7405. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  7406. if ret == 'fail':
  7407. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  7408. "Attempting to create a FlatCAM CNCJob Object from "
  7409. "G-Code file failed during processing"))
  7410. return "fail"
  7411. # Register recent file
  7412. self.file_opened.emit("cncjob", filename)
  7413. # GUI feedback
  7414. self.inform.emit(_("[success] Opened: %s") % filename)
  7415. self.progress.emit(100)
  7416. def open_config_file(self, filename, run_from_arg=None):
  7417. """
  7418. Loads a config file from the specified file.
  7419. :param filename: Name of the file from which to load.
  7420. :type filename: str
  7421. :return: None
  7422. """
  7423. App.log.debug("Opening config file: " + filename)
  7424. # add the tab if it was closed
  7425. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7426. # first clear previous text in text editor (if any)
  7427. self.ui.code_editor.clear()
  7428. # Switch plot_area to CNCJob tab
  7429. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7430. try:
  7431. if filename:
  7432. f = QtCore.QFile(filename)
  7433. if f.open(QtCore.QIODevice.ReadOnly):
  7434. stream = QtCore.QTextStream(f)
  7435. gcode_edited = stream.readAll()
  7436. self.ui.code_editor.setPlainText(gcode_edited)
  7437. f.close()
  7438. except IOError:
  7439. App.log.error("Failed to open config file: %s" % filename)
  7440. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  7441. return
  7442. def open_project(self, filename, run_from_arg=None):
  7443. """
  7444. Loads a project from the specified file.
  7445. 1) Loads and parses file
  7446. 2) Registers the file as recently opened.
  7447. 3) Calls on_file_new()
  7448. 4) Updates options
  7449. 5) Calls new_object() with the object's from_dict() as init method.
  7450. 6) Calls plot_all()
  7451. :param filename: Name of the file from which to load.
  7452. :type filename: str
  7453. :param run_from_arg: True if run for arguments
  7454. :return: None
  7455. """
  7456. App.log.debug("Opening project: " + filename)
  7457. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7458. # Open and parse an uncompressed Project file
  7459. try:
  7460. f = open(filename, 'r')
  7461. except IOError:
  7462. App.log.error("Failed to open project file: %s" % filename)
  7463. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  7464. return
  7465. try:
  7466. d = json.load(f, object_hook=dict2obj)
  7467. except Exception as e:
  7468. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7469. (filename, str(e)))
  7470. f.close()
  7471. # Open and parse a compressed Project file
  7472. try:
  7473. with lzma.open(filename) as f:
  7474. file_content = f.read().decode('utf-8')
  7475. d = json.loads(file_content, object_hook=dict2obj)
  7476. except Exception as e:
  7477. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7478. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  7479. return
  7480. # Clear the current project
  7481. # # NOT THREAD SAFE # ##
  7482. if run_from_arg is True:
  7483. pass
  7484. else:
  7485. self.on_file_new()
  7486. # Project options
  7487. self.options.update(d['options'])
  7488. self.project_filename = filename
  7489. self.set_screen_units(self.options["units"])
  7490. # Re create objects
  7491. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7492. for obj in d['objs']:
  7493. def obj_init(obj_inst, app_inst):
  7494. obj_inst.from_dict(obj)
  7495. App.log.debug("Recreating from opened project an %s object: %s" %
  7496. (obj['kind'].capitalize(), obj['options']['name']))
  7497. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  7498. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7499. # self.plot_all()
  7500. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  7501. self.should_we_save = False
  7502. self.file_opened.emit("project", filename)
  7503. self.set_ui_title(name=self.project_filename)
  7504. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7505. def propagate_defaults(self, silent=False):
  7506. """
  7507. This method is used to set default values in classes. It's
  7508. an alternative to project options but allows the use
  7509. of values invisible to the user.
  7510. :return: None
  7511. """
  7512. if silent is False:
  7513. self.log.debug("propagate_defaults()")
  7514. # Which objects to update the given parameters.
  7515. routes = {
  7516. "global_zdownrate": CNCjob,
  7517. "excellon_zeros": Excellon,
  7518. "excellon_format_upper_in": Excellon,
  7519. "excellon_format_lower_in": Excellon,
  7520. "excellon_format_upper_mm": Excellon,
  7521. "excellon_format_lower_mm": Excellon,
  7522. "excellon_units": Excellon,
  7523. "gerber_use_buffer_for_union": Gerber,
  7524. "geometry_multidepth": Geometry
  7525. }
  7526. for param in routes:
  7527. if param in routes[param].defaults:
  7528. try:
  7529. routes[param].defaults[param] = self.defaults[param]
  7530. if silent is False:
  7531. self.log.debug(" " + param + " OK")
  7532. except KeyError:
  7533. if silent is False:
  7534. self.log.debug(" ERROR: " + param + " not in defaults.")
  7535. else:
  7536. # Try extracting the name:
  7537. # classname_param here is param in the object
  7538. if param.find(routes[param].__name__.lower() + "_") == 0:
  7539. p = param[len(routes[param].__name__) + 1:]
  7540. if p in routes[param].defaults:
  7541. routes[param].defaults[p] = self.defaults[param]
  7542. if silent is False:
  7543. self.log.debug(" " + param + " OK!")
  7544. def restore_main_win_geom(self):
  7545. try:
  7546. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7547. self.defaults["global_def_win_y"],
  7548. self.defaults["global_def_win_w"],
  7549. self.defaults["global_def_win_h"])
  7550. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7551. settings = QSettings("Open Source", "FlatCAM")
  7552. if settings.contains("maximized_gui"):
  7553. maximized_ui = settings.value('maximized_gui', type=bool)
  7554. if maximized_ui is True:
  7555. self.ui.showMaximized()
  7556. except KeyError as e:
  7557. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7558. def plot_all(self, zoom=True):
  7559. """
  7560. Re-generates all plots from all objects.
  7561. :return: None
  7562. """
  7563. self.log.debug("Plot_all()")
  7564. for obj in self.collection.get_list():
  7565. def worker_task(obj):
  7566. with self.proc_container.new("Plotting"):
  7567. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7568. if zoom:
  7569. self.object_plotted.emit(obj)
  7570. # Send to worker
  7571. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7572. def register_folder(self, filename):
  7573. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7574. def register_save_folder(self, filename):
  7575. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7576. def set_progress_bar(self, percentage, text=""):
  7577. self.ui.progress_bar.setValue(int(percentage))
  7578. def setup_shell(self):
  7579. """
  7580. Creates shell functions. Runs once at startup.
  7581. :return: None
  7582. """
  7583. self.log.debug("setup_shell()")
  7584. def shelp(p=None):
  7585. if not p:
  7586. return _("Available commands:\n") + \
  7587. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7588. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7589. if p not in commands:
  7590. return "Unknown command: %s" % p
  7591. return commands[p]["help"]
  7592. # --- Migrated to new architecture ---
  7593. # def options(name):
  7594. # ops = self.collection.get_by_name(str(name)).options
  7595. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7596. def h(*args):
  7597. """
  7598. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7599. and standalone parameters into list.
  7600. """
  7601. kwa = {}
  7602. a = []
  7603. n = len(args)
  7604. name = None
  7605. for i in range(n):
  7606. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7607. if match:
  7608. assert name is None
  7609. name = match.group(1)
  7610. continue
  7611. if name is None:
  7612. a.append(args[i])
  7613. else:
  7614. kwa[name] = args[i]
  7615. name = None
  7616. return a, kwa
  7617. @contextmanager
  7618. def wait_signal(signal, timeout=10000):
  7619. """
  7620. Block loop until signal emitted, timeout (ms) elapses
  7621. or unhandled exception happens in a thread.
  7622. :param timeout: time after which the loop is exited
  7623. :param signal: Signal to wait for.
  7624. """
  7625. loop = QtCore.QEventLoop()
  7626. # Normal termination
  7627. signal.connect(loop.quit)
  7628. # Termination by exception in thread
  7629. self.thread_exception.connect(loop.quit)
  7630. status = {'timed_out': False}
  7631. def report_quit():
  7632. status['timed_out'] = True
  7633. loop.quit()
  7634. yield
  7635. # Temporarily change how exceptions are managed.
  7636. oeh = sys.excepthook
  7637. ex = []
  7638. def except_hook(type_, value, traceback_):
  7639. ex.append(value)
  7640. oeh(type_, value, traceback_)
  7641. sys.excepthook = except_hook
  7642. # Terminate on timeout
  7643. if timeout is not None:
  7644. QtCore.QTimer.singleShot(timeout, report_quit)
  7645. # # ## Block ## ##
  7646. loop.exec_()
  7647. # Restore exception management
  7648. sys.excepthook = oeh
  7649. if ex:
  7650. self.raiseTclError(str(ex[0]))
  7651. if status['timed_out']:
  7652. raise Exception('Timed out!')
  7653. def make_docs():
  7654. output = ''
  7655. import collections
  7656. od = collections.OrderedDict(sorted(commands.items()))
  7657. for cmd_, val in od.items():
  7658. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7659. t = val['help']
  7660. usage_i = t.find('>')
  7661. if usage_i < 0:
  7662. expl = t
  7663. output += expl + '\n\n'
  7664. continue
  7665. expl = t[:usage_i - 1]
  7666. output += expl + '\n\n'
  7667. end_usage_i = t[usage_i:].find('\n')
  7668. if end_usage_i < 0:
  7669. end_usage_i = len(t[usage_i:])
  7670. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7671. else:
  7672. extras = t[usage_i+end_usage_i+1:]
  7673. parts = [s.strip() for s in extras.split('\n')]
  7674. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7675. for p in parts:
  7676. output += ' ' + p + '\n\n'
  7677. return output
  7678. '''
  7679. Howto implement TCL shell commands:
  7680. All parameters passed to command should be possible to set as None and test it afterwards.
  7681. This is because we need to see error caused in tcl,
  7682. if None value as default parameter is not allowed TCL will return empty error.
  7683. Use:
  7684. def mycommand(name=None,...):
  7685. Test it like this:
  7686. if name is None:
  7687. self.raise_tcl_error('Argument name is missing.')
  7688. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7689. otherwise we will miss it and processing will silently continue.
  7690. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7691. which is catched in exec_command and displayed in TCL shell console with red background.
  7692. Error in console is displayed with TCL trace.
  7693. This behavior works only within main thread,
  7694. errors with promissed tasks can be catched and detected only with log.
  7695. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7696. TCL shell.
  7697. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7698. '''
  7699. commands = {
  7700. 'help': {
  7701. 'fcn': shelp,
  7702. 'help': _("Shows list of commands.")
  7703. },
  7704. }
  7705. # Import/overwrite tcl commands as objects of TclCommand descendants
  7706. # This modifies the variable 'commands'.
  7707. tclCommands.register_all_commands(self, commands)
  7708. # Add commands to the tcl interpreter
  7709. for cmd in commands:
  7710. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7711. # Make the tcl puts function return instead of print to stdout
  7712. self.tcl.eval('''
  7713. rename puts original_puts
  7714. proc puts {args} {
  7715. if {[llength $args] == 1} {
  7716. return "[lindex $args 0]"
  7717. } else {
  7718. eval original_puts $args
  7719. }
  7720. }
  7721. ''')
  7722. def setup_recent_items(self):
  7723. # TODO: Move this to constructor
  7724. icons = {
  7725. "gerber": "share/flatcam_icon16.png",
  7726. "excellon": "share/drill16.png",
  7727. 'geometry': "share/geometry16.png",
  7728. "cncjob": "share/cnc16.png",
  7729. "project": "share/project16.png",
  7730. "svg": "share/geometry16.png",
  7731. "dxf": "share/dxf16.png",
  7732. "pdf": "share/pdf32.png",
  7733. "image": "share/image16.png"
  7734. }
  7735. openers = {
  7736. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7737. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7738. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7739. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7740. 'project': self.open_project,
  7741. 'svg': self.import_svg,
  7742. 'dxf': self.import_dxf,
  7743. 'image': self.import_image,
  7744. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7745. }
  7746. # Open recent file for files
  7747. try:
  7748. f = open(self.data_path + '/recent.json')
  7749. except IOError:
  7750. App.log.error("Failed to load recent item list.")
  7751. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  7752. return
  7753. try:
  7754. self.recent = json.load(f)
  7755. except json.scanner.JSONDecodeError:
  7756. App.log.error("Failed to parse recent item list.")
  7757. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  7758. f.close()
  7759. return
  7760. f.close()
  7761. # Open recent file for projects
  7762. try:
  7763. fp = open(self.data_path + '/recent_projects.json')
  7764. except IOError:
  7765. App.log.error("Failed to load recent project item list.")
  7766. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent projects item list."))
  7767. return
  7768. try:
  7769. self.recent_projects = json.load(fp)
  7770. except json.scanner.JSONDecodeError:
  7771. App.log.error("Failed to parse recent project item list.")
  7772. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent project item list."))
  7773. fp.close()
  7774. return
  7775. fp.close()
  7776. # Closure needed to create callbacks in a loop.
  7777. # Otherwise late binding occurs.
  7778. def make_callback(func, fname):
  7779. def opener():
  7780. func(fname)
  7781. return opener
  7782. def reset_recent_files():
  7783. # Reset menu
  7784. self.ui.recent.clear()
  7785. self.recent = []
  7786. try:
  7787. f = open(self.data_path + '/recent.json', 'w')
  7788. except IOError:
  7789. App.log.error("Failed to open recent items file for writing.")
  7790. return
  7791. json.dump(self.recent, f)
  7792. def reset_recent_projects():
  7793. # Reset menu
  7794. self.ui.recent_projects.clear()
  7795. self.recent_projects = []
  7796. try:
  7797. fp = open(self.data_path + '/recent_projects.json', 'w')
  7798. except IOError:
  7799. App.log.error("Failed to open recent projects items file for writing.")
  7800. return
  7801. json.dump(self.recent, fp)
  7802. # Reset menu
  7803. self.ui.recent.clear()
  7804. self.ui.recent_projects.clear()
  7805. # Create menu items for projects
  7806. for recent in self.recent_projects:
  7807. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7808. if recent['kind'] == 'project':
  7809. try:
  7810. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7811. # Attach callback
  7812. o = make_callback(openers[recent["kind"]], recent['filename'])
  7813. action.triggered.connect(o)
  7814. self.ui.recent_projects.addAction(action)
  7815. except KeyError:
  7816. App.log.error("Unsupported file type: %s" % recent["kind"])
  7817. # Last action in Recent Files menu is one that Clear the content
  7818. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7819. clear_action_proj.triggered.connect(reset_recent_projects)
  7820. self.ui.recent_projects.addSeparator()
  7821. self.ui.recent_projects.addAction(clear_action_proj)
  7822. # Create menu items for files
  7823. for recent in self.recent:
  7824. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7825. if recent['kind'] != 'project':
  7826. try:
  7827. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7828. # Attach callback
  7829. o = make_callback(openers[recent["kind"]], recent['filename'])
  7830. action.triggered.connect(o)
  7831. self.ui.recent.addAction(action)
  7832. except KeyError:
  7833. App.log.error("Unsupported file type: %s" % recent["kind"])
  7834. # Last action in Recent Files menu is one that Clear the content
  7835. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7836. clear_action.triggered.connect(reset_recent_files)
  7837. self.ui.recent.addSeparator()
  7838. self.ui.recent.addAction(clear_action)
  7839. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7840. # self.ui.menufilerecent.set_submenu(recent_menu)
  7841. # recent_menu.show_all()
  7842. # self.ui.recent.show()
  7843. self.log.debug("Recent items list has been populated.")
  7844. def setup_component_editor(self):
  7845. # label = QtWidgets.QLabel("Choose an item from Project")
  7846. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7847. sel_title = QtWidgets.QTextEdit(
  7848. _('<b>Shortcut Key List</b>'))
  7849. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7850. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7851. settings = QSettings("Open Source", "FlatCAM")
  7852. if settings.contains("notebook_font_size"):
  7853. fsize = settings.value('notebook_font_size', type=int)
  7854. else:
  7855. fsize = 12
  7856. tsize = fsize + int(fsize / 2)
  7857. selected_text = (_('''
  7858. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  7859. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7860. The normal flow when working in FlatCAM is the following:</span></p>
  7861. <ol>
  7862. <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  7863. <br />
  7864. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  7865. &nbsp;</li>
  7866. <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7867. <br />
  7868. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  7869. <br />
  7870. You can change the parameters in this screen and the flow direction is like this:<br />
  7871. <br />
  7872. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7873. </ol>
  7874. <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  7875. ''').format(fsize=fsize, tsize=tsize))
  7876. sel_title.setText(selected_text)
  7877. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7878. self.ui.selected_scroll_area.setWidget(sel_title)
  7879. def setup_obj_classes(self):
  7880. """
  7881. Sets up application specifics on the FlatCAMObj class.
  7882. :return: None
  7883. """
  7884. FlatCAMObj.app = self
  7885. ObjectCollection.app = self
  7886. Gerber.app = self
  7887. Excellon.app = self
  7888. Geometry.app = self
  7889. CNCjob.app = self
  7890. FCProcess.app = self
  7891. FCProcessContainer.app = self
  7892. def version_check(self):
  7893. """
  7894. Checks for the latest version of the program. Alerts the
  7895. user if theirs is outdated. This method is meant to be run
  7896. in a separate thread.
  7897. :return: None
  7898. """
  7899. self.log.debug("version_check()")
  7900. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7901. full_url = App.version_url + \
  7902. "?s=" + str(self.defaults['global_serial']) + \
  7903. "&v=" + str(self.version) + \
  7904. "&os=" + str(self.os) + \
  7905. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  7906. else:
  7907. # no_stats dict; just so it won't break things on website
  7908. no_ststs_dict = {}
  7909. no_ststs_dict["global_ststs"] = {}
  7910. full_url = App.version_url + \
  7911. "?s=" + str(self.defaults['global_serial']) + \
  7912. "&v=" + str(self.version) + \
  7913. "&os=" + str(self.os) + \
  7914. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7915. App.log.debug("Checking for updates @ %s" % full_url)
  7916. # ## Get the data
  7917. try:
  7918. f = urllib.request.urlopen(full_url)
  7919. except:
  7920. # App.log.warning("Failed checking for latest version. Could not connect.")
  7921. self.log.warning("Failed checking for latest version. Could not connect.")
  7922. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  7923. return
  7924. try:
  7925. data = json.load(f)
  7926. except Exception as e:
  7927. App.log.error("Could not parse information about latest version.")
  7928. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  7929. App.log.debug("json.load(): %s" % str(e))
  7930. f.close()
  7931. return
  7932. f.close()
  7933. # ## Latest version?
  7934. if self.version >= data["version"]:
  7935. App.log.debug("FlatCAM is up to date!")
  7936. self.inform.emit(_("[success] FlatCAM is up to date!"))
  7937. return
  7938. App.log.debug("Newer version available.")
  7939. self.message.emit(
  7940. _("Newer Version Available"),
  7941. _("There is a newer version of FlatCAM available for download:\n\n") +
  7942. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  7943. _("info")
  7944. )
  7945. def on_plotcanvas_setup(self, container=None):
  7946. """
  7947. This is doing the setup for the plot area (VisPy canvas)
  7948. :param container: widget where to install the canvas
  7949. :return: None
  7950. """
  7951. if container:
  7952. plot_container = container
  7953. else:
  7954. plot_container = self.ui.right_layout
  7955. self.plotcanvas = PlotCanvas(plot_container, self)
  7956. # So it can receive key presses
  7957. self.plotcanvas.native.setFocus()
  7958. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  7959. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  7960. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7961. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  7962. # Keys over plot enabled
  7963. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  7964. self.app_cursor = self.plotcanvas.new_cursor()
  7965. self.app_cursor.enabled = False
  7966. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7967. def on_zoom_fit(self, event):
  7968. """
  7969. Callback for zoom-out request. This can be either from the corresponding
  7970. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7971. with axes limits from the geometry bounds of all objects.
  7972. :param event: Ignored.
  7973. :return: None
  7974. """
  7975. self.plotcanvas.fit_view()
  7976. def on_zoom_in(self):
  7977. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7978. def on_zoom_out(self):
  7979. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7980. def disable_all_plots(self):
  7981. self.report_usage("disable_all_plots()")
  7982. self.disable_plots(self.collection.get_list())
  7983. self.inform.emit(_("[success] All plots disabled."))
  7984. def disable_other_plots(self):
  7985. self.report_usage("disable_other_plots()")
  7986. self.disable_plots(self.collection.get_non_selected())
  7987. self.inform.emit(_("[success] All non selected plots disabled."))
  7988. def enable_all_plots(self):
  7989. self.report_usage("enable_all_plots()")
  7990. self.enable_plots(self.collection.get_list())
  7991. self.inform.emit(_("[success] All plots enabled."))
  7992. def on_enable_sel_plots(self):
  7993. log.debug("App.on_enable_sel_plot()")
  7994. object_list = self.collection.get_selected()
  7995. self.enable_plots(objects=object_list)
  7996. self.inform.emit(_("[success] Selected plots enabled..."))
  7997. def on_disable_sel_plots(self):
  7998. log.debug("App.on_disable_sel_plot()")
  7999. # self.inform.emit(_("Disabling plots ..."))
  8000. object_list = self.collection.get_selected()
  8001. self.disable_plots(objects=object_list)
  8002. self.inform.emit(_("[success] Selected plots disabled..."))
  8003. def enable_plots(self, objects):
  8004. """
  8005. Disables plots
  8006. :param objects: list of Objects to be enabled
  8007. :return:
  8008. """
  8009. log.debug("Enabling plots ...")
  8010. # self.inform.emit(_("Working ..."))
  8011. for obj in objects:
  8012. if obj.options['plot'] is False:
  8013. obj.options.set_change_callback(lambda x: None)
  8014. obj.options['plot'] = True
  8015. obj.options.set_change_callback(obj.on_options_change)
  8016. def worker_task(objects):
  8017. with self.proc_container.new(_("Enabling plots ...")):
  8018. for obj in objects:
  8019. # obj.options['plot'] = True
  8020. if isinstance(obj, FlatCAMCNCjob):
  8021. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8022. else:
  8023. obj.plot(visible=True)
  8024. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8025. # self.plots_updated.emit()
  8026. def disable_plots(self, objects):
  8027. """
  8028. Disables plots
  8029. :param objects: list of Objects to be disabled
  8030. :return:
  8031. """
  8032. # if no objects selected then do nothing
  8033. if not self.collection.get_selected():
  8034. return
  8035. log.debug("Disabling plots ...")
  8036. # self.inform.emit(_("Working ..."))
  8037. for obj in objects:
  8038. if obj.options['plot'] is True:
  8039. obj.options.set_change_callback(lambda x: None)
  8040. obj.options['plot'] = False
  8041. obj.options.set_change_callback(obj.on_options_change)
  8042. # self.plots_updated.emit()
  8043. def worker_task(objects):
  8044. with self.proc_container.new(_("Disabling plots ...")):
  8045. for obj in objects:
  8046. # obj.options['plot'] = True
  8047. if isinstance(obj, FlatCAMCNCjob):
  8048. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8049. else:
  8050. obj.plot(visible=False)
  8051. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8052. def toggle_plots(self, objects):
  8053. """
  8054. Toggle plots visibility
  8055. :param objects: list of Objects for which to be toggled the visibility
  8056. :return:
  8057. """
  8058. # if no objects selected then do nothing
  8059. if not self.collection.get_selected():
  8060. return
  8061. log.debug("Toggling plots ...")
  8062. self.inform.emit(_("Working ..."))
  8063. for obj in objects:
  8064. if obj.options['plot'] is False:
  8065. obj.options['plot'] = True
  8066. else:
  8067. obj.options['plot'] = False
  8068. self.plots_updated.emit()
  8069. def clear_plots(self):
  8070. objects = self.collection.get_list()
  8071. for obj in objects:
  8072. obj.clear(obj == objects[-1])
  8073. # Clear pool to free memory
  8074. self.clear_pool()
  8075. def generate_cnc_job(self, objects):
  8076. self.report_usage("generate_cnc_job()")
  8077. # for obj in objects:
  8078. # obj.generatecncjob()
  8079. for obj in objects:
  8080. obj.on_generatecnc_button_click()
  8081. def save_project(self, filename, quit_action=False):
  8082. """
  8083. Saves the current project to the specified file.
  8084. :param filename: Name of the file in which to save.
  8085. :type filename: str
  8086. :param quit_action: if the project saving will be followed by an app quit; boolean
  8087. :return: None
  8088. """
  8089. self.log.debug("save_project()")
  8090. self.save_in_progress = True
  8091. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8092. # Capture the latest changes
  8093. # Current object
  8094. try:
  8095. self.collection.get_active().read_form()
  8096. except:
  8097. self.log.debug("There was no active object")
  8098. pass
  8099. # Project options
  8100. self.options_read_form()
  8101. # Serialize the whole project
  8102. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8103. "options": self.options,
  8104. "version": self.version}
  8105. if self.defaults["global_save_compressed"] is True:
  8106. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8107. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8108. # # Write
  8109. f.write(g)
  8110. self.inform.emit(_("[success] Project saved to: %s") % filename)
  8111. else:
  8112. # Open file
  8113. try:
  8114. f = open(filename, 'w')
  8115. except IOError:
  8116. App.log.error("Failed to open file for saving: %s", filename)
  8117. return
  8118. # Write
  8119. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8120. f.close()
  8121. # verification of the saved project
  8122. # Open and parse
  8123. try:
  8124. saved_f = open(filename, 'r')
  8125. except IOError:
  8126. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  8127. return
  8128. try:
  8129. saved_d = json.load(saved_f, object_hook=dict2obj)
  8130. except:
  8131. self.inform.emit(
  8132. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  8133. f.close()
  8134. return
  8135. saved_f.close()
  8136. if 'version' in saved_d:
  8137. self.inform.emit(_("[success] Project saved to: %s") % filename)
  8138. else:
  8139. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  8140. settings = QSettings("Open Source", "FlatCAM")
  8141. lock_state = self.ui.lock_action.isChecked()
  8142. settings.setValue('toolbar_lock', lock_state)
  8143. # This will write the setting to the platform specific storage.
  8144. del settings
  8145. # if quit:
  8146. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8147. # t.start()
  8148. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8149. def start_delayed_quit(self, delay, filename, should_quit=None):
  8150. """
  8151. :param delay: period of checking if project file size is more than zero; in seconds
  8152. :param filename: the name of the project file to be checked periodically for size more than zero
  8153. :param should_quit: if the task finished will be followed by an app quit; boolean
  8154. :return:
  8155. """
  8156. to_quit = should_quit
  8157. self.save_timer = QtCore.QTimer()
  8158. self.save_timer.setInterval(delay)
  8159. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8160. self.save_timer.start()
  8161. def check_project_file_size(self, filename, should_quit=None):
  8162. """
  8163. :param filename: the name of the project file to be checked periodically for size more than zero
  8164. :param should_quit: will quit the app if True; boolean
  8165. :return:
  8166. """
  8167. try:
  8168. if os.stat(filename).st_size > 0:
  8169. self.save_in_progress = False
  8170. self.save_timer.stop()
  8171. if should_quit:
  8172. self.app_quit.emit()
  8173. except Exception as e:
  8174. traceback.print_exc()
  8175. def on_options_app2project(self):
  8176. """
  8177. Callback for Options->Transfer Options->App=>Project. Copies options
  8178. from application defaults to project defaults.
  8179. :return: None
  8180. """
  8181. self.report_usage("on_options_app2project")
  8182. self.defaults_read_form()
  8183. self.options.update(self.defaults)
  8184. self.options_write_form()
  8185. def on_options_project2app(self):
  8186. """
  8187. Callback for Options->Transfer Options->Project=>App. Copies options
  8188. from project defaults to application defaults.
  8189. :return: None
  8190. """
  8191. self.report_usage("on_options_project2app")
  8192. self.options_read_form()
  8193. self.defaults.update(self.options)
  8194. self.defaults_write_form()
  8195. def on_options_project2object(self):
  8196. """
  8197. Callback for Options->Transfer Options->Project=>Object. Copies options
  8198. from project defaults to the currently selected object.
  8199. :return: None
  8200. """
  8201. self.report_usage("on_options_project2object")
  8202. self.options_read_form()
  8203. obj = self.collection.get_active()
  8204. if obj is None:
  8205. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  8206. return
  8207. for option in self.options:
  8208. if option.find(obj.kind + "_") == 0:
  8209. oname = option[len(obj.kind) + 1:]
  8210. obj.options[oname] = self.options[option]
  8211. obj.to_form() # Update UI
  8212. def on_options_object2project(self):
  8213. """
  8214. Callback for Options->Transfer Options->Object=>Project. Copies options
  8215. from the currently selected object to project defaults.
  8216. :return: None
  8217. """
  8218. self.report_usage("on_options_object2project")
  8219. obj = self.collection.get_active()
  8220. if obj is None:
  8221. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  8222. return
  8223. obj.read_form()
  8224. for option in obj.options:
  8225. if option in ['name']: # TODO: Handle this better...
  8226. continue
  8227. self.options[obj.kind + "_" + option] = obj.options[option]
  8228. self.options_write_form()
  8229. def on_options_object2app(self):
  8230. """
  8231. Callback for Options->Transfer Options->Object=>App. Copies options
  8232. from the currently selected object to application defaults.
  8233. :return: None
  8234. """
  8235. self.report_usage("on_options_object2app")
  8236. obj = self.collection.get_active()
  8237. if obj is None:
  8238. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  8239. return
  8240. obj.read_form()
  8241. for option in obj.options:
  8242. if option in ['name']: # TODO: Handle this better...
  8243. continue
  8244. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8245. self.defaults_write_form()
  8246. def on_options_app2object(self):
  8247. """
  8248. Callback for Options->Transfer Options->App=>Object. Copies options
  8249. from application defaults to the currently selected object.
  8250. :return: None
  8251. """
  8252. self.report_usage("on_options_app2object")
  8253. self.defaults_read_form()
  8254. obj = self.collection.get_active()
  8255. if obj is None:
  8256. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  8257. return
  8258. for option in self.defaults:
  8259. if option.find(obj.kind + "_") == 0:
  8260. oname = option[len(obj.kind) + 1:]
  8261. obj.options[oname] = self.defaults[option]
  8262. obj.to_form() # Update UI
  8263. class ArgsThread(QtCore.QObject):
  8264. open_signal = pyqtSignal(list)
  8265. start = pyqtSignal()
  8266. if sys.platform == 'win32':
  8267. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8268. else:
  8269. address = ('/tmp/testipc', 'AF_UNIX')
  8270. def __init__(self):
  8271. super(ArgsThread, self).__init__()
  8272. self.start.connect(self.run)
  8273. def my_loop(self, address):
  8274. try:
  8275. listener = Listener(*address)
  8276. while True:
  8277. conn = listener.accept()
  8278. self.serve(conn)
  8279. except socket.error as e:
  8280. conn = Client(*address)
  8281. conn.send(sys.argv)
  8282. conn.send('close')
  8283. # close the current instance only if there are args
  8284. if len(sys.argv) > 1:
  8285. sys.exit()
  8286. def serve(self, conn):
  8287. while True:
  8288. msg = conn.recv()
  8289. if msg == 'close':
  8290. break
  8291. self.open_signal.emit(msg)
  8292. conn.close()
  8293. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8294. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8295. @pyqtSlot()
  8296. def run(self):
  8297. self.my_loop(self.address)
  8298. class GracefulException(Exception):
  8299. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8300. def __init__(self):
  8301. super().__init__()
  8302. def __str__(self):
  8303. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8304. # end of file