app_Main.py 472 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500
  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. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from appCommon.Common import LoudDict
  39. from appCommon.Common import color_variant
  40. from appCommon.Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray, FCInputDialogSlider
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = "Unstable Version"
  138. # version = 8.994
  139. version_date = "2020/10/30"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal([str], [str, bool])
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, qapp, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. App.log.info("FlatCAM Starting...")
  222. self.qapp = qapp
  223. # ############################################################################################################
  224. # ################# Setup the listening thread for another instance launching with args ######################
  225. # ############################################################################################################
  226. if sys.platform == 'win32' or sys.platform == 'linux':
  227. # make sure the thread is stored by using a self. otherwise it's garbage collected
  228. self.listen_th = QtCore.QThread()
  229. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  230. self.new_launch = ArgsThread()
  231. self.new_launch.open_signal[list].connect(self.on_startup_args)
  232. self.new_launch.moveToThread(self.listen_th)
  233. self.new_launch.start.emit()
  234. # ############################################################################################################
  235. # ########################################## OS-specific #####################################################
  236. # ############################################################################################################
  237. portable = False
  238. # Folder for user settings.
  239. if sys.platform == 'win32':
  240. if platform.architecture()[0] == '32bit':
  241. App.log.debug("Win32!")
  242. else:
  243. App.log.debug("Win64!")
  244. # #######################################################################################################
  245. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  246. # #######################################################################################################
  247. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  248. try:
  249. with open(config_file, 'r'):
  250. pass
  251. except FileNotFoundError:
  252. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  253. try:
  254. with open(config_file, 'r') as f:
  255. try:
  256. for line in f:
  257. param = str(line).replace('\n', '').rpartition('=')
  258. if param[0] == 'portable':
  259. try:
  260. portable = eval(param[2])
  261. except NameError:
  262. portable = False
  263. if param[0] == 'headless':
  264. if param[2].lower() == 'true':
  265. self.cmd_line_headless = 1
  266. else:
  267. self.cmd_line_headless = None
  268. except Exception as e:
  269. log.debug('App.__init__() -->%s' % str(e))
  270. return
  271. except FileNotFoundError as e:
  272. log.debug(str(e))
  273. pass
  274. if portable is False:
  275. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  276. else:
  277. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  278. self.os = 'windows'
  279. else: # Linux/Unix/MacOS
  280. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  281. self.os = 'unix'
  282. # ############################################################################################################
  283. # ################################# Setup folders and files ##################################################
  284. # ############################################################################################################
  285. if not os.path.exists(self.data_path):
  286. os.makedirs(self.data_path)
  287. App.log.debug('Created data folder: ' + self.data_path)
  288. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  289. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  290. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  291. if not os.path.exists(self.preprocessorpaths):
  292. os.makedirs(self.preprocessorpaths)
  293. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  294. # create tools_db.FlatDB file if there is none
  295. try:
  296. f = open(self.data_path + '/tools_db.FlatDB')
  297. f.close()
  298. except IOError:
  299. App.log.debug('Creating empty tools_db.FlatDB')
  300. f = open(self.data_path + '/tools_db.FlatDB', 'w')
  301. json.dump({}, f)
  302. f.close()
  303. # create current_defaults.FlatConfig file if there is none
  304. try:
  305. f = open(self.data_path + '/current_defaults.FlatConfig')
  306. f.close()
  307. except IOError:
  308. App.log.debug('Creating empty current_defaults.FlatConfig')
  309. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  310. json.dump({}, f)
  311. f.close()
  312. # the factory defaults are written only once at the first launch of the application after installation
  313. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  314. # create a recent files json file if there is none
  315. try:
  316. f = open(self.data_path + '/recent.json')
  317. f.close()
  318. except IOError:
  319. App.log.debug('Creating empty recent.json')
  320. f = open(self.data_path + '/recent.json', 'w')
  321. json.dump([], f)
  322. f.close()
  323. # create a recent projects json file if there is none
  324. try:
  325. fp = open(self.data_path + '/recent_projects.json')
  326. fp.close()
  327. except IOError:
  328. App.log.debug('Creating empty recent_projects.json')
  329. fp = open(self.data_path + '/recent_projects.json', 'w')
  330. json.dump([], fp)
  331. fp.close()
  332. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  333. # This will fail under cx_freeze ...
  334. self.app_home = os.path.dirname(os.path.realpath(__file__))
  335. log.debug("Application path is " + self.app_home)
  336. log.debug("Started in " + os.getcwd())
  337. # cx_freeze workaround
  338. if os.path.isfile(self.app_home):
  339. self.app_home = os.path.dirname(self.app_home)
  340. os.chdir(self.app_home)
  341. # ############################################################################################################
  342. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  343. # ############################################################################################################
  344. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  345. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  346. if user_defaults:
  347. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  348. if self.defaults['units'] == 'MM':
  349. self.decimals = int(self.defaults['decimals_metric'])
  350. else:
  351. self.decimals = int(self.defaults['decimals_inch'])
  352. if self.defaults["global_gray_icons"] is False:
  353. self.resource_location = 'assets/resources'
  354. else:
  355. self.resource_location = 'assets/resources/dark_resources'
  356. self.current_units = self.defaults['units']
  357. # ###########################################################################################################
  358. # #################################### SETUP OBJECT CLASSES #################################################
  359. # ###########################################################################################################
  360. self.setup_obj_classes()
  361. # ###########################################################################################################
  362. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  363. # ###########################################################################################################
  364. self.pool = Pool()
  365. # ###########################################################################################################
  366. # ###################################### Clear GUI Settings - once at first start ###########################
  367. # ###########################################################################################################
  368. if self.defaults["first_run"] is True:
  369. # on first run clear the previous QSettings, therefore clearing the GUI settings
  370. qsettings = QSettings("Open Source", "FlatCAM")
  371. for key in qsettings.allKeys():
  372. qsettings.remove(key)
  373. # This will write the setting to the platform specific storage.
  374. del qsettings
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. self.splash = None
  401. show_splash = 0
  402. # ###########################################################################################################
  403. # ######################################### Initialize GUI ##################################################
  404. # ###########################################################################################################
  405. # FlatCAM colors used in plotting
  406. self.FC_light_green = '#BBF268BF'
  407. self.FC_dark_green = '#006E20BF'
  408. self.FC_light_blue = '#a5a5ffbf'
  409. self.FC_dark_blue = '#0000ffbf'
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui = MainGUI(self)
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # #################################### LOAD PREPROCESSORS ###################################################
  436. # ###########################################################################################################
  437. # ----------------------------------------- WARNING --------------------------------------------------------
  438. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  439. # That's because the number of preprocessors can vary and here the comboboxes are populated
  440. # -----------------------------------------------------------------------------------------------------------
  441. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  442. # the preprocessor file
  443. self.preprocessors = load_preprocessors(self)
  444. # make sure that always the 'default' preprocessor is the first item in the dictionary
  445. if 'default' in self.preprocessors.keys():
  446. new_ppp_dict = {}
  447. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  448. default_pp = self.preprocessors.pop('default')
  449. new_ppp_dict['default'] = default_pp
  450. # then add the rest of the keys
  451. for name, val_class in self.preprocessors.items():
  452. new_ppp_dict[name] = val_class
  453. # and now put back the ordered dict with 'default' key first
  454. self.preprocessors = new_ppp_dict
  455. # populate the Preprocessor ComboBoxes in the PREFERENCES
  456. for name in list(self.preprocessors.keys()):
  457. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  458. if name.partition('_')[0] == 'Paste':
  459. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  460. continue
  461. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  462. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  463. if name == 'hpgl':
  464. continue
  465. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  466. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  467. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  468. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  469. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  470. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  471. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  472. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  473. QtCore.Qt.ToolTipRole)
  474. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  475. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  476. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  477. QtCore.Qt.ToolTipRole)
  478. # ###########################################################################################################
  479. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  480. # ###########################################################################################################
  481. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  482. inform=self.inform)
  483. self.preferencesUiManager.defaults_write_form()
  484. # When the self.defaults dictionary changes will update the Preferences GUI forms
  485. self.defaults.set_change_callback(self.on_defaults_dict_change)
  486. # ###########################################################################################################
  487. # ##################################### FIRST RUN SECTION ###################################################
  488. # ################################ It's done only once after install #####################################
  489. # ###########################################################################################################
  490. if self.defaults["first_run"] is True:
  491. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  492. initial_lay = 'minimal'
  493. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  494. # Set the combobox in Preferences to the current layout
  495. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  496. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  497. # after the first run, this object should be False
  498. self.defaults["first_run"] = False
  499. self.preferencesUiManager.save_defaults(silent=True)
  500. # ###########################################################################################################
  501. # ############################################ Data #########################################################
  502. # ###########################################################################################################
  503. self.recent = []
  504. self.recent_projects = []
  505. self.clipboard = QtWidgets.QApplication.clipboard()
  506. self.project_filename = None
  507. self.toggle_units_ignore = False
  508. self.main_thread = QtWidgets.QApplication.instance().thread()
  509. # ###########################################################################################################
  510. # ########################################## LOAD LANGUAGES ################################################
  511. # ###########################################################################################################
  512. self.languages = fcTranslate.load_languages()
  513. for name in sorted(self.languages.values()):
  514. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  515. # ###########################################################################################################
  516. # ####################################### APPLY APP LANGUAGE ################################################
  517. # ###########################################################################################################
  518. ret_val = fcTranslate.apply_language('strings')
  519. if ret_val == "no language":
  520. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  521. log.debug("Could not find the Language files. The App strings are missing.")
  522. else:
  523. # make the current language the current selection on the language combobox
  524. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  525. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  526. # ###########################################################################################################
  527. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  528. # ###########################################################################################################
  529. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  530. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  531. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  532. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  533. self.defaults.propagate_defaults()
  534. # ###########################################################################################################
  535. # ######################################## UPDATE THE OPTIONS ###############################################
  536. # ###########################################################################################################
  537. self.options = LoudDict()
  538. # -----------------------------------------------------------------------------------------------------------
  539. # Update the self.options from the self.defaults
  540. # The self.defaults holds the application defaults while the self.options holds the object defaults
  541. # -----------------------------------------------------------------------------------------------------------
  542. # Copy app defaults to project options
  543. for def_key, def_val in self.defaults.items():
  544. self.options[def_key] = deepcopy(def_val)
  545. self.preferencesUiManager.show_preferences_gui()
  546. # ### End of Data ####
  547. # ###########################################################################################################
  548. # #################################### SETUP OBJECT COLLECTION ##############################################
  549. # ###########################################################################################################
  550. self.collection = ObjectCollection(app=self)
  551. self.ui.project_tab_layout.addWidget(self.collection.view)
  552. self.app_obj = AppObject(app=self)
  553. # ### Adjust tabs width ## ##
  554. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  555. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  556. self.collection.view.setMinimumWidth(290)
  557. self.log.debug("Finished creating Object Collection.")
  558. # ###########################################################################################################
  559. # ######################################## SETUP Plot Area ##################################################
  560. # ###########################################################################################################
  561. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  562. if self.defaults["global_graphic_engine"] == '3D':
  563. self.is_legacy = False
  564. else:
  565. self.is_legacy = True
  566. # Event signals disconnect id holders
  567. self.mp = None
  568. self.mm = None
  569. self.mr = None
  570. self.mdc = None
  571. self.mp_zc = None
  572. self.kp = None
  573. # Matplotlib axis
  574. self.axes = None
  575. if show_splash:
  576. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  577. "Canvas initialization started."),
  578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  579. color=QtGui.QColor("gray"))
  580. start_plot_time = time.time() # debug
  581. self.plotcanvas = None
  582. self.app_cursor = None
  583. self.hover_shapes = None
  584. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  585. # setup the PlotCanvas
  586. self.on_plotcanvas_setup()
  587. end_plot_time = time.time()
  588. self.used_time = end_plot_time - start_plot_time
  589. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  590. if show_splash:
  591. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  592. "Canvas initialization started.\n"
  593. "Canvas initialization finished in"), '%.2f' % self.used_time),
  594. alignment=Qt.AlignBottom | Qt.AlignLeft,
  595. color=QtGui.QColor("gray"))
  596. self.ui.splitter.setStretchFactor(1, 2)
  597. # ###########################################################################################################
  598. # ############################################### Worker SETUP ##############################################
  599. # ###########################################################################################################
  600. if self.defaults["global_worker_number"]:
  601. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  602. else:
  603. self.workers = WorkerStack(workers_number=2)
  604. self.worker_task.connect(self.workers.add_task)
  605. self.log.debug("Finished creating Workers crew.")
  606. # ###########################################################################################################
  607. # ############################################# Activity Monitor ############################################
  608. # ###########################################################################################################
  609. # self.activity_view = FlatCAMActivityView(app=self)
  610. # self.ui.infobar.addWidget(self.activity_view)
  611. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  612. # ###########################################################################################################
  613. # ########################################## Other setups ###################################################
  614. # ###########################################################################################################
  615. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  616. # depending on from where those tools are called different actions can be done
  617. self.call_source = 'app'
  618. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  619. self.tool_tab_locked = False
  620. # decide if to show or hide the Notebook side of the screen at startup
  621. if self.defaults["global_project_at_startup"] is True:
  622. self.ui.splitter.setSizes([1, 1])
  623. else:
  624. self.ui.splitter.setSizes([0, 1])
  625. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  626. self.setup_default_properties_tab()
  627. # ###########################################################################################################
  628. # ####################################### Auto-complete KEYWORDS ############################################
  629. # ###########################################################################################################
  630. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  631. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  632. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  633. 'export_exc',
  634. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  635. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  636. 'interiors', 'isolate', 'join_excellon',
  637. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  638. 'mirror', 'ncc',
  639. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  640. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  641. 'options', 'origin',
  642. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  643. 'save', 'save_project',
  644. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  645. 'skew', 'subtract_poly', 'subtract_rectangle',
  646. 'version', 'write_gcode'
  647. ]
  648. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  649. 'Paste_1',
  650. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  651. 'Toolchange_manual', 'True', 'Users',
  652. 'all', 'auto', 'axis',
  653. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  654. 'contour', 'default',
  655. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  656. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  657. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  658. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  659. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  660. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  661. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  662. 'spacing_columns',
  663. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  664. 'toolchange_xy', 'toolchangez', 'travelz',
  665. 'tooldia', 'use_threads', 'value',
  666. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  667. ]
  668. self.tcl_keywords = [
  669. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  670. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  671. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  672. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  673. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  674. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  675. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  676. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  677. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  678. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  679. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  680. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  681. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  682. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  683. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  684. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  685. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  686. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  687. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  688. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  689. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  690. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  691. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  692. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  693. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  694. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  695. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  696. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  697. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  698. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  699. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  700. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  701. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  702. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  703. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  704. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  705. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  706. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  707. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  708. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  709. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  710. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  711. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  712. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  713. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  714. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  715. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  716. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  717. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  718. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  719. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  720. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  721. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  722. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  723. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  724. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  725. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  726. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  727. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  728. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  729. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  730. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  731. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  732. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  733. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  734. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  735. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  736. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  737. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  738. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  739. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  740. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  741. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  742. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  743. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  744. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  745. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  746. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  747. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  748. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  749. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  750. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  751. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  752. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  753. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  754. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  755. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  756. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  757. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  758. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  759. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  760. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  761. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  762. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  763. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  764. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  765. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  766. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  767. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  768. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  769. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  770. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  771. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  772. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  773. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  774. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  775. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  776. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  777. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  778. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  779. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  780. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  781. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  782. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  783. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  784. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  785. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  786. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  787. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  788. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  789. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  790. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  791. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  792. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  793. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  794. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  795. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  796. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  797. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  798. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  799. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  800. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  801. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  802. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  803. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  804. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  805. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  806. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  807. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  808. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  809. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  810. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  811. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  812. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  813. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  814. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  815. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  816. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  817. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  818. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  819. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  820. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  821. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  822. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  823. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  824. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  825. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  826. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  827. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  828. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  829. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  830. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  831. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  832. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  833. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  834. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  835. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  836. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  837. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  838. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  839. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  840. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  841. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  842. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  843. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  844. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  845. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  846. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  847. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  848. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  849. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  850. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  851. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  852. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  853. ]
  854. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  855. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  856. # ###########################################################################################################
  857. # ########################################## Tools and Plugins ##############################################
  858. # ###########################################################################################################
  859. self.shell = None
  860. self.dblsidedtool = None
  861. self.distance_tool = None
  862. self.distance_min_tool = None
  863. self.panelize_tool = None
  864. self.film_tool = None
  865. self.paste_tool = None
  866. self.calculator_tool = None
  867. self.rules_tool = None
  868. self.sub_tool = None
  869. self.move_tool = None
  870. self.cutout_tool = None
  871. self.ncclear_tool = None
  872. self.paint_tool = None
  873. self.isolation_tool = None
  874. self.drilling_tool = None
  875. self.optimal_tool = None
  876. self.transform_tool = None
  877. self.properties_tool = None
  878. self.pdf_tool = None
  879. self.image_tool = None
  880. self.pcb_wizard_tool = None
  881. self.cal_exc_tool = None
  882. self.qrcode_tool = None
  883. self.copper_thieving_tool = None
  884. self.fiducial_tool = None
  885. self.edrills_tool = None
  886. self.align_objects_tool = None
  887. self.punch_tool = None
  888. self.invert_tool = None
  889. self.corners_tool = None
  890. self.etch_tool = None
  891. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  892. try:
  893. self.install_tools()
  894. except AttributeError as e:
  895. log.debug("App.__init__() install_tools() --> %s" % str(e))
  896. # ###########################################################################################################
  897. # ######################################### BookMarks Manager ###############################################
  898. # ###########################################################################################################
  899. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  900. self.install_bookmarks()
  901. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  902. # ###########################################################################################################
  903. # ########################################### Tools Database ################################################
  904. # ###########################################################################################################
  905. self.tools_db_tab = None
  906. # ### System Font Parsing ###
  907. # self.f_parse = ParseFont(self)
  908. # self.parse_system_fonts()
  909. # ###########################################################################################################
  910. # ############################################## Shell SETUP ################################################
  911. # ###########################################################################################################
  912. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  913. if self.defaults["global_shell_at_startup"]:
  914. self.ui.shell_dock.show()
  915. else:
  916. self.ui.shell_dock.hide()
  917. # ###########################################################################################################
  918. # ######################################### Check for updates ###############################################
  919. # ###########################################################################################################
  920. # Separate thread (Not worker)
  921. # Check for updates on startup but only if the user consent and the app is not in Beta version
  922. if (self.beta is False or self.beta is None) and \
  923. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  924. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  925. # self.thr2 = QtCore.QThread()
  926. self.worker_task.emit({'fcn': self.version_check,
  927. 'params': []})
  928. # self.thr2.start(QtCore.QThread.LowPriority)
  929. # ###########################################################################################################
  930. # ##################################### Register files with FlatCAM; #######################################
  931. # ################################### It works only for Windows for now ####################################
  932. # ###########################################################################################################
  933. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  934. self.on_register_files()
  935. # ###########################################################################################################
  936. # ######################################## Variables for global usage #######################################
  937. # ###########################################################################################################
  938. # hold the App units
  939. self.units = 'MM'
  940. # coordinates for relative position display
  941. self.rel_point1 = (0, 0)
  942. self.rel_point2 = (0, 0)
  943. # variable to store coordinates
  944. self.pos = (0, 0)
  945. self.pos_canvas = (0, 0)
  946. self.pos_jump = (0, 0)
  947. # variable to store mouse coordinates
  948. self.mouse = [0, 0]
  949. # variable to store the delta positions on cavnas
  950. self.dx = 0
  951. self.dy = 0
  952. # decide if we have a double click or single click
  953. self.doubleclick = False
  954. # store here the is_dragging value
  955. self.event_is_dragging = False
  956. # variable to store if a command is active (then the var is not None) and which one it is
  957. self.command_active = None
  958. # variable to store the status of moving selection action
  959. # None value means that it's not an selection action
  960. # True value = a selection from left to right
  961. # False value = a selection from right to left
  962. self.selection_type = None
  963. # List to store the objects that are currently loaded in FlatCAM
  964. # This list is updated on each object creation or object delete
  965. self.all_objects_list = []
  966. self.objects_under_the_click_list = []
  967. # List to store the objects that are selected
  968. self.sel_objects_list = []
  969. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  970. self.key_modifiers = None
  971. # Variable to store the status of the code editor
  972. self.toggle_codeeditor = False
  973. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  974. self.click_noproject = False
  975. self.cursor = None
  976. # Variable to store the GCODE that was edited
  977. self.gcode_edited = ""
  978. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  979. self.old_state_of_tools_toolbar = False
  980. self.text_editor_tab = None
  981. # reference for the self.ui.code_editor
  982. self.reference_code_editor = None
  983. self.script_code = ''
  984. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  985. self.tools_db_changed_flag = False
  986. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  987. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  988. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  989. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  990. 'tsm']
  991. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  992. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  993. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  994. 'sbp', 'tap', 'xpi']
  995. self.svg_list = ['svg']
  996. self.dxf_list = ['dxf']
  997. self.pdf_list = ['pdf']
  998. self.prj_list = ['flatprj']
  999. self.conf_list = ['flatconfig']
  1000. # last used filters
  1001. self.last_op_gerber_filter = None
  1002. self.last_op_excellon_filter = None
  1003. self.last_op_gcode_filter = None
  1004. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1005. # flag for polygons not cleared
  1006. self.poly_not_cleared = False
  1007. # VisPy visuals
  1008. self.isHovering = False
  1009. self.notHovering = True
  1010. # Window geometry
  1011. self.x_pos = None
  1012. self.y_pos = None
  1013. self.width = None
  1014. self.height = None
  1015. # when True, the app has to return from any thread
  1016. self.abort_flag = False
  1017. # set the value used in the Windows Title
  1018. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1019. # this holds a widget that is installed in the Plot Area when View Source option is used
  1020. self.source_editor_tab = None
  1021. self.pagesize = {}
  1022. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1023. # VisPy visuals
  1024. if self.is_legacy is False:
  1025. try:
  1026. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1027. except AttributeError:
  1028. self.tool_shapes = None
  1029. else:
  1030. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1031. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1032. # used in the delayed shutdown self.start_delayed_quit() method
  1033. self.save_timer = None
  1034. # ###########################################################################################################
  1035. # ################################## ADDING FlatCAM EDITORS section #########################################
  1036. # ###########################################################################################################
  1037. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1038. # at the first launch of the App , the editors will not be functional.
  1039. try:
  1040. self.geo_editor = AppGeoEditor(self)
  1041. except Exception as es:
  1042. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1043. try:
  1044. self.exc_editor = AppExcEditor(self)
  1045. except Exception as es:
  1046. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1047. try:
  1048. self.grb_editor = AppGerberEditor(self)
  1049. except Exception as es:
  1050. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1051. try:
  1052. self.gcode_editor = AppGCodeEditor(self)
  1053. except Exception as es:
  1054. log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1055. self.log.debug("Finished adding FlatCAM Editor's.")
  1056. self.set_ui_title(name=_("New Project - Not saved"))
  1057. current_platform = platform.architecture()[0]
  1058. if current_platform != '64bit':
  1059. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1060. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1061. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1062. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1063. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1064. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1065. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1066. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1067. # ###########################################################################################################
  1068. # ########################################### EXCLUSION AREAS ###############################################
  1069. # ###########################################################################################################
  1070. self.exc_areas = ExclusionAreas(app=self)
  1071. # ###########################################################################################################
  1072. # ###########################################################################################################
  1073. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1074. # ###########################################################################################################
  1075. # ###########################################################################################################
  1076. self.f_handlers = MenuFileHandlers(app=self)
  1077. # this is calculated in the class above (somehow?)
  1078. self.defaults["root_folder_path"] = self.app_home
  1079. # ###########################################################################################################
  1080. # ############################################### SYS TRAY ##################################################
  1081. # ###########################################################################################################
  1082. if self.defaults["global_systray_icon"]:
  1083. self.parent_w = QtWidgets.QWidget()
  1084. if self.cmd_line_headless == 1:
  1085. self.trayIcon = FlatCAMSystemTray(app=self,
  1086. icon=QtGui.QIcon(self.resource_location +
  1087. '/flatcam_icon32_green.png'),
  1088. headless=True,
  1089. parent=self.parent_w)
  1090. else:
  1091. self.trayIcon = FlatCAMSystemTray(app=self,
  1092. icon=QtGui.QIcon(self.resource_location +
  1093. '/flatcam_icon32_green.png'),
  1094. parent=self.parent_w)
  1095. # ###########################################################################################################
  1096. # ############################################ SETUP RECENT ITEMS ###########################################
  1097. # ###########################################################################################################
  1098. self.setup_recent_items()
  1099. # ###########################################################################################################
  1100. # ###########################################################################################################
  1101. # ############################################# Signal handling #############################################
  1102. # ###########################################################################################################
  1103. # ###########################################################################################################
  1104. # ########################################## Custom signals ################################################
  1105. # signal for displaying messages in status bar
  1106. self.inform[str].connect(self.info)
  1107. self.inform[str, bool].connect(self.info)
  1108. # signal for displaying messages in the shell
  1109. self.inform_shell[str].connect(self.info_shell)
  1110. self.inform_shell[str, bool].connect(self.info_shell)
  1111. # signal to be called when the app is quiting
  1112. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1113. self.message.connect(lambda: message_dialog(parent=self.ui))
  1114. # self.progress.connect(self.set_progress_bar)
  1115. # signals emitted when file state change
  1116. self.file_opened.connect(self.register_recent)
  1117. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1118. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1119. # when the defaults dictionary values change
  1120. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1121. # ########################################## Standard signals ###############################################
  1122. # ### Menu
  1123. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1124. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1125. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1126. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1127. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1128. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1129. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1130. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1131. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1132. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1133. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1134. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1135. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1136. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1137. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1138. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1139. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1140. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1141. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1142. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1143. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1144. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1145. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1146. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1147. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1148. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1149. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1150. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1151. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1152. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1153. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1154. self.ui.menufile_exit.triggered.connect(self.final_save)
  1155. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1156. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1157. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1158. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1159. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1160. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1161. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1162. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1163. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1164. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1165. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1166. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1167. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1168. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1169. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1170. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1171. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1172. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1173. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1174. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1175. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1176. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1177. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1178. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1179. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1180. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1181. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1182. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1183. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1184. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1185. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1186. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1187. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1188. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1189. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1190. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1191. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1192. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1193. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1194. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1195. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1196. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1197. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1198. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1199. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1200. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1201. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1202. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1203. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1204. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1205. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1206. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1207. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  1208. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1209. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1210. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1211. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1212. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1213. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1214. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1215. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1216. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1217. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1218. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1219. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1220. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1221. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1222. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1223. # ToolBar signals
  1224. self.connect_toolbar_signals(ui=self.ui)
  1225. # Context Menu
  1226. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1227. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1228. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1229. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1230. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1231. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1232. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1233. self.ui.clearplot.triggered.connect(self.clear_plots)
  1234. self.ui.replot.triggered.connect(self.plot_all)
  1235. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1236. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1237. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1238. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1239. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1240. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1241. # Project Context Menu -> Color Setting
  1242. for act in self.ui.menuprojectcolor.actions():
  1243. act.triggered.connect(self.on_set_color_action_triggered)
  1244. # Notebook tab clicking
  1245. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1246. # ###########################################################################################################
  1247. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1248. # ###########################################################################################################
  1249. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1250. lambda: self.on_toggle_units(no_pref=False))
  1251. # ##################################### Workspace Setting Signals ###########################################
  1252. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1253. self.on_workspace_modified)
  1254. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1255. self.on_workspace_modified
  1256. )
  1257. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1258. # ###########################################################################################################
  1259. # ######################################## GUI SETTINGS SIGNALS #############################################
  1260. # ###########################################################################################################
  1261. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1262. # ######################################## Tools related signals ############################################
  1263. # portability changed signal
  1264. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1265. # Object list
  1266. self.object_status_changed.connect(self.collection.on_collection_updated)
  1267. # when there are arguments at application startup this get launched
  1268. self.args_at_startup[list].connect(self.on_startup_args)
  1269. # ###########################################################################################################
  1270. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1271. # ###########################################################################################################
  1272. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1273. lambda: self.restore_extensions(ext_type='excellon'))
  1274. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1275. lambda: self.restore_extensions(ext_type='gcode'))
  1276. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1277. lambda: self.restore_extensions(ext_type='gerber'))
  1278. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1279. lambda: self.delete_all_extensions(ext_type='excellon'))
  1280. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1281. lambda: self.delete_all_extensions(ext_type='gcode'))
  1282. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1283. lambda: self.delete_all_extensions(ext_type='gerber'))
  1284. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1285. lambda: self.add_extension(ext_type='excellon'))
  1286. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1287. lambda: self.add_extension(ext_type='gcode'))
  1288. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1289. lambda: self.add_extension(ext_type='gerber'))
  1290. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1291. lambda: self.del_extension(ext_type='excellon'))
  1292. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1293. lambda: self.del_extension(ext_type='gcode'))
  1294. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1295. lambda: self.del_extension(ext_type='gerber'))
  1296. # connect the 'Apply' buttons from the Preferences/File Associations
  1297. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1298. lambda: self.on_register_files(obj_type='excellon'))
  1299. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1300. lambda: self.on_register_files(obj_type='gcode'))
  1301. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1302. lambda: self.on_register_files(obj_type='gerber'))
  1303. # ###########################################################################################################
  1304. # ########################################### KEYWORDS SIGNALS ##############################################
  1305. # ###########################################################################################################
  1306. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1307. lambda: self.restore_extensions(ext_type='keyword'))
  1308. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1309. lambda: self.delete_all_extensions(ext_type='keyword'))
  1310. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1311. lambda: self.add_extension(ext_type='keyword'))
  1312. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1313. lambda: self.del_extension(ext_type='keyword'))
  1314. # ###########################################################################################################
  1315. # ########################################### GUI SIGNALS ###################################################
  1316. # ###########################################################################################################
  1317. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1318. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1319. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1320. # ###########################################################################################################
  1321. # ####################################### VARIOUS SIGNALS ###################################################
  1322. # ###########################################################################################################
  1323. # connect the abort_all_tasks related slots to the related signals
  1324. self.proc_container.idle_flag.connect(self.app_is_idle)
  1325. # signal emitted when a tab is closed in the Plot Area
  1326. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1327. # signal to close the application
  1328. self.close_app_signal.connect(self.kill_app)
  1329. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1330. # ###########################################################################################################
  1331. # ###########################################################################################################
  1332. # ###########################################################################################################
  1333. self.log.debug("Finished connecting Signals.")
  1334. # ###########################################################################################################
  1335. # ##################################### Finished the CONSTRUCTOR ############################################
  1336. # ###########################################################################################################
  1337. App.log.debug("END of constructor. Releasing control.")
  1338. # ###########################################################################################################
  1339. # ########################################## SHOW GUI #######################################################
  1340. # ###########################################################################################################
  1341. # if the app is not started as headless, show it
  1342. if self.cmd_line_headless != 1:
  1343. if show_splash:
  1344. # finish the splash
  1345. self.splash.finish(self.ui)
  1346. mgui_settings = QSettings("Open Source", "FlatCAM")
  1347. if mgui_settings.contains("maximized_gui"):
  1348. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1349. if maximized_ui is True:
  1350. self.ui.showMaximized()
  1351. else:
  1352. self.ui.show()
  1353. else:
  1354. self.ui.show()
  1355. if self.defaults["global_systray_icon"]:
  1356. self.trayIcon.show()
  1357. else:
  1358. log.warning("******************* RUNNING HEADLESS *******************")
  1359. # ###########################################################################################################
  1360. # ######################################## START-UP ARGUMENTS ###############################################
  1361. # ###########################################################################################################
  1362. # test if the program was started with a script as parameter
  1363. if self.cmd_line_shellvar:
  1364. try:
  1365. cnt = 0
  1366. command_tcl = 0
  1367. for i in self.cmd_line_shellvar.split(','):
  1368. if i is not None:
  1369. # noinspection PyBroadException
  1370. try:
  1371. command_tcl = eval(i)
  1372. except Exception:
  1373. command_tcl = i
  1374. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1375. cnt += 1
  1376. # if there are Windows paths then replace the path separator with a Unix like one
  1377. if sys.platform == 'win32':
  1378. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1379. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1380. except Exception as ext:
  1381. print("ERROR: ", ext)
  1382. sys.exit(2)
  1383. if self.cmd_line_shellfile:
  1384. if self.cmd_line_headless != 1:
  1385. if self.ui.shell_dock.isHidden():
  1386. self.ui.shell_dock.show()
  1387. try:
  1388. with open(self.cmd_line_shellfile, "r") as myfile:
  1389. # if show_splash:
  1390. # self.splash.showMessage('%s: %ssec\n%s' % (
  1391. # _("Canvas initialization started.\n"
  1392. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1393. # _("Executing Tcl Script ...")),
  1394. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1395. # color=QtGui.QColor("gray"))
  1396. cmd_line_shellfile_text = myfile.read()
  1397. if self.cmd_line_headless != 1:
  1398. self.shell.exec_command(cmd_line_shellfile_text)
  1399. else:
  1400. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1401. except Exception as ext:
  1402. print("ERROR: ", ext)
  1403. sys.exit(2)
  1404. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1405. # the path/file_name must be enclosed in quotes if it contain spaces
  1406. if App.args:
  1407. self.args_at_startup.emit(App.args)
  1408. if self.defaults.old_defaults_found is True:
  1409. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1410. "Please reboot the application to update."))
  1411. self.defaults.old_defaults_found = False
  1412. # ######################################### INIT FINISHED #######################################################
  1413. # #################################################################################################################
  1414. # #################################################################################################################
  1415. # #################################################################################################################
  1416. # #################################################################################################################
  1417. # #################################################################################################################
  1418. @staticmethod
  1419. def copy_and_overwrite(from_path, to_path):
  1420. """
  1421. From here:
  1422. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1423. :param from_path: source path
  1424. :param to_path: destination path
  1425. :return: None
  1426. """
  1427. if os.path.exists(to_path):
  1428. shutil.rmtree(to_path)
  1429. try:
  1430. shutil.copytree(from_path, to_path)
  1431. except FileNotFoundError:
  1432. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1433. shutil.copytree(from_new_path, to_path)
  1434. def on_startup_args(self, args, silent=False):
  1435. """
  1436. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1437. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1438. :param args: a list containing the application args at startup
  1439. :return: None
  1440. """
  1441. if args is not None:
  1442. args_to_process = args
  1443. else:
  1444. args_to_process = App.args
  1445. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1446. for argument in args_to_process:
  1447. if '.FlatPrj'.lower() in argument.lower():
  1448. try:
  1449. project_name = str(argument)
  1450. if project_name == "":
  1451. if silent is False:
  1452. self.inform.emit(_("Cancelled."))
  1453. else:
  1454. # self.open_project(project_name)
  1455. run_from_arg = True
  1456. # self.worker_task.emit({'fcn': self.open_project,
  1457. # 'params': [project_name, run_from_arg]})
  1458. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1459. except Exception as e:
  1460. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1461. elif '.FlatConfig'.lower() in argument.lower():
  1462. try:
  1463. file_name = str(argument)
  1464. if file_name == "":
  1465. if silent is False:
  1466. self.inform.emit(_("Open Config file failed."))
  1467. else:
  1468. run_from_arg = True
  1469. # self.worker_task.emit({'fcn': self.open_config_file,
  1470. # 'params': [file_name, run_from_arg]})
  1471. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1472. except Exception as e:
  1473. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1474. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1475. try:
  1476. file_name = str(argument)
  1477. if file_name == "":
  1478. if silent is False:
  1479. self.inform.emit(_("Open Script file failed."))
  1480. else:
  1481. if silent is False:
  1482. self.on_fileopenscript(name=file_name)
  1483. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1484. self.on_filerunscript(name=file_name)
  1485. except Exception as e:
  1486. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1487. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1488. log.debug("App.on_startup_args() --> Quit event.")
  1489. sys.exit()
  1490. elif 'save'.lower() in argument.lower():
  1491. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1492. self.preferencesUiManager.save_defaults()
  1493. else:
  1494. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1495. proc_arg = argument.lower()
  1496. for ext in exc_list:
  1497. proc_ext = ext.replace(' ', '')
  1498. proc_ext = '.%s' % proc_ext
  1499. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1500. file_name = str(argument)
  1501. if file_name == "":
  1502. if silent is False:
  1503. self.inform.emit(_("Open Excellon file failed."))
  1504. else:
  1505. self.on_fileopenexcellon(name=file_name, signal=None)
  1506. return
  1507. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1508. for ext in gco_list:
  1509. proc_ext = ext.replace(' ', '')
  1510. proc_ext = '.%s' % proc_ext
  1511. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1512. file_name = str(argument)
  1513. if file_name == "":
  1514. if silent is False:
  1515. self.inform.emit(_("Open GCode file failed."))
  1516. else:
  1517. self.on_fileopengcode(name=file_name, signal=None)
  1518. return
  1519. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1520. for ext in grb_list:
  1521. proc_ext = ext.replace(' ', '')
  1522. proc_ext = '.%s' % proc_ext
  1523. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1524. file_name = str(argument)
  1525. if file_name == "":
  1526. if silent is False:
  1527. self.inform.emit(_("Open Gerber file failed."))
  1528. else:
  1529. self.on_fileopengerber(name=file_name, signal=None)
  1530. return
  1531. # if it reached here without already returning then the app was registered with a file that it does not
  1532. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1533. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1534. # for arg in args_to_process:
  1535. # if 'FlatCAM.exe' in arg:
  1536. # continue
  1537. # else:
  1538. # sys.exit(2)
  1539. def set_ui_title(self, name):
  1540. """
  1541. Sets the title of the main window.
  1542. :param name: String that store the project path and project name
  1543. :return: None
  1544. """
  1545. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1546. (self.version,
  1547. ('BETA' if self.beta else ''),
  1548. platform.architecture()[0],
  1549. self.engine,
  1550. name)
  1551. )
  1552. def on_app_restart(self):
  1553. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1554. # be left in the SySTray
  1555. try:
  1556. self.trayIcon.hide()
  1557. except Exception:
  1558. pass
  1559. fcTranslate.restart_program(app=self)
  1560. def clear_pool(self):
  1561. """
  1562. Clear the multiprocessing pool and calls garbage collector.
  1563. :return: None
  1564. """
  1565. self.pool.close()
  1566. self.pool = Pool()
  1567. self.pool_recreated.emit(self.pool)
  1568. gc.collect()
  1569. def install_tools(self):
  1570. """
  1571. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1572. Instantiation of the Tools classes.
  1573. The order that the tools are installed is important as they can depend on each other install position.
  1574. :return: None
  1575. """
  1576. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1577. self.shell = FCShell(app=self, version=self.version)
  1578. self.distance_tool = Distance(self)
  1579. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1580. before=self.ui.menueditorigin,
  1581. separator=False)
  1582. self.distance_min_tool = DistanceMin(self)
  1583. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1584. pos=self.ui.menuedit,
  1585. before=self.ui.menueditorigin,
  1586. separator=True)
  1587. self.dblsidedtool = DblSidedTool(self)
  1588. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1589. self.cal_exc_tool = ToolCalibration(self)
  1590. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1591. before=self.dblsidedtool.menuAction,
  1592. separator=False)
  1593. self.align_objects_tool = AlignObjects(self)
  1594. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1595. self.edrills_tool = ToolExtractDrills(self)
  1596. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1597. self.panelize_tool = Panelize(self)
  1598. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1599. self.film_tool = Film(self)
  1600. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1601. self.paste_tool = SolderPaste(self)
  1602. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1603. self.calculator_tool = ToolCalculator(self)
  1604. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1605. self.sub_tool = ToolSub(self)
  1606. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1607. pos=self.ui.menutool, separator=True)
  1608. self.rules_tool = RulesCheck(self)
  1609. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1610. pos=self.ui.menutool, separator=False)
  1611. self.optimal_tool = ToolOptimal(self)
  1612. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1613. pos=self.ui.menutool, separator=True)
  1614. self.move_tool = ToolMove(self)
  1615. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1616. before=self.ui.menueditorigin, separator=True)
  1617. self.cutout_tool = CutOut(self)
  1618. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1619. before=self.sub_tool.menuAction)
  1620. self.ncclear_tool = NonCopperClear(self)
  1621. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1622. before=self.sub_tool.menuAction, separator=True)
  1623. self.paint_tool = ToolPaint(self)
  1624. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1625. before=self.sub_tool.menuAction, separator=True)
  1626. self.isolation_tool = ToolIsolation(self)
  1627. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1628. before=self.sub_tool.menuAction, separator=True)
  1629. self.drilling_tool = ToolDrilling(self)
  1630. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1631. before=self.sub_tool.menuAction, separator=True)
  1632. self.copper_thieving_tool = ToolCopperThieving(self)
  1633. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1634. pos=self.ui.menutool)
  1635. self.fiducial_tool = ToolFiducials(self)
  1636. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1637. pos=self.ui.menutool)
  1638. self.qrcode_tool = QRCode(self)
  1639. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1640. pos=self.ui.menutool)
  1641. self.punch_tool = ToolPunchGerber(self)
  1642. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1643. self.invert_tool = ToolInvertGerber(self)
  1644. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1645. self.corners_tool = ToolCorners(self)
  1646. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1647. self.etch_tool = ToolEtchCompensation(self)
  1648. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1649. self.transform_tool = ToolTransform(self)
  1650. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1651. pos=self.ui.menuoptions, separator=True)
  1652. self.properties_tool = Properties(self)
  1653. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1654. pos=self.ui.menuoptions)
  1655. self.pdf_tool = ToolPDF(self)
  1656. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1657. pos=self.ui.menufileimport,
  1658. separator=True)
  1659. self.image_tool = ToolImage(self)
  1660. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1661. pos=self.ui.menufileimport,
  1662. separator=True)
  1663. self.pcb_wizard_tool = PcbWizard(self)
  1664. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1665. pos=self.ui.menufileimport)
  1666. self.log.debug("Tools are installed.")
  1667. def remove_tools(self):
  1668. """
  1669. Will remove all the actions in the Tool menu.
  1670. :return: None
  1671. """
  1672. for act in self.ui.menutool.actions():
  1673. self.ui.menutool.removeAction(act)
  1674. def init_tools(self):
  1675. """
  1676. Initialize the Tool tab in the notebook side of the central widget.
  1677. Remove the actions in the Tools menu.
  1678. Instantiate again the FlatCAM tools (plugins).
  1679. All this is required when changing the layout: standard, compact etc.
  1680. :return: None
  1681. """
  1682. log.debug("init_tools()")
  1683. # delete the data currently in the Tools Tab and the Tab itself
  1684. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1685. if widget is not None:
  1686. widget.deleteLater()
  1687. self.ui.notebook.removeTab(2)
  1688. # rebuild the Tools Tab
  1689. self.ui.tool_tab = QtWidgets.QWidget()
  1690. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1691. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1692. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1693. self.ui.tool_scroll_area = VerticalScrollArea()
  1694. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1695. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1696. # first remove all of them
  1697. self.remove_tools()
  1698. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1699. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1700. '&Command Line\tS')
  1701. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1702. # third install all of them
  1703. try:
  1704. self.install_tools()
  1705. except AttributeError:
  1706. pass
  1707. self.log.debug("Tools are initialized.")
  1708. # def parse_system_fonts(self):
  1709. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1710. # 'params': []})
  1711. def connect_tools_signals_to_toolbar(self, ui):
  1712. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1713. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1714. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1715. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1716. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1717. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1718. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1719. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1720. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1721. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1722. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1723. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1724. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1725. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1726. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1727. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1728. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1729. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1730. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1731. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1732. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1733. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1734. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1735. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1736. def connect_toolbar_signals(self, ui):
  1737. """
  1738. Reconnect the signals to the actions in the toolbar.
  1739. This has to be done each time after the FlatCAM tools are removed/installed.
  1740. :return: None
  1741. """
  1742. # Toolbar
  1743. # File Toolbar Signals
  1744. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1745. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1746. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1747. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1748. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1749. # View Toolbar Signals
  1750. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1751. ui.replot_btn.triggered.connect(self.plot_all)
  1752. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1753. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1754. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1755. # Edit Toolbar Signals
  1756. ui.editgeo_btn.triggered.connect(self.object2editor)
  1757. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1758. ui.copy_btn.triggered.connect(self.on_copy_command)
  1759. ui.delete_btn.triggered.connect(self.on_delete)
  1760. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1761. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1762. ui.origin_btn.triggered.connect(self.on_set_origin)
  1763. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1764. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1765. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1766. # Scripting Toolbar Signals
  1767. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1768. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1769. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1770. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1771. # Tools Toolbar Signals
  1772. try:
  1773. self.connect_tools_signals_to_toolbar(ui=ui)
  1774. except Exception as err:
  1775. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1776. def object2editor(self):
  1777. """
  1778. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1779. :return: None
  1780. """
  1781. self.defaults.report_usage("object2editor()")
  1782. # disable the objects menu as it may interfere with the appEditors
  1783. self.ui.menuobjects.setDisabled(True)
  1784. edited_object = self.collection.get_active()
  1785. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1786. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1787. pass
  1788. else:
  1789. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1790. return
  1791. if isinstance(edited_object, GeometryObject):
  1792. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1793. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1794. # we set the notebook to hidden
  1795. # self.ui.splitter.setSizes([0, 1])
  1796. if edited_object.multigeo is True:
  1797. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1798. if len(sel_rows) > 1:
  1799. self.inform.emit('[WARNING_NOTCL] %s' %
  1800. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1801. "is not possible.\n"
  1802. "Edit only one geometry at a time."))
  1803. if not sel_rows:
  1804. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1805. return
  1806. # determine the tool dia of the selected tool
  1807. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1808. # now find the key in the edited_object.tools that has this tooldia
  1809. multi_tool = 1
  1810. for tool in edited_object.tools:
  1811. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1812. multi_tool = tool
  1813. break
  1814. log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1815. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1816. else:
  1817. log.debug("Editing SingleGeo Geometry with tool diameter.")
  1818. self.geo_editor.edit_fcgeometry(edited_object)
  1819. # set call source to the Editor we go into
  1820. self.call_source = 'geo_editor'
  1821. elif isinstance(edited_object, ExcellonObject):
  1822. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1823. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1824. if self.ui.splitter.sizes()[0] == 0:
  1825. self.ui.splitter.setSizes([1, 1])
  1826. self.exc_editor.edit_fcexcellon(edited_object)
  1827. # set call source to the Editor we go into
  1828. self.call_source = 'exc_editor'
  1829. elif isinstance(edited_object, GerberObject):
  1830. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1831. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1832. if self.ui.splitter.sizes()[0] == 0:
  1833. self.ui.splitter.setSizes([1, 1])
  1834. self.grb_editor.edit_fcgerber(edited_object)
  1835. # set call source to the Editor we go into
  1836. self.call_source = 'grb_editor'
  1837. # reset the following variables so the UI is built again after edit
  1838. edited_object.ui_build = False
  1839. elif isinstance(edited_object, CNCJobObject):
  1840. if self.ui.splitter.sizes()[0] == 0:
  1841. self.ui.splitter.setSizes([1, 1])
  1842. # set call source to the Editor we go into
  1843. self.call_source = 'gcode_editor'
  1844. self.gcode_editor.edit_fcgcode(edited_object)
  1845. # make sure that we can't select another object while in Editor Mode:
  1846. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1847. self.ui.project_frame.setDisabled(True)
  1848. # delete any selection shape that might be active as they are not relevant in Editor
  1849. self.delete_selection_shape()
  1850. # hide the Tools Toolbar
  1851. tools_tb = self.ui.toolbartools
  1852. if tools_tb.isVisible():
  1853. self.old_state_of_tools_toolbar = True
  1854. tools_tb.hide()
  1855. else:
  1856. self.old_state_of_tools_toolbar = False
  1857. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1858. self.ui.plot_tab_area.protectTab(0)
  1859. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1860. self.should_we_save = True
  1861. def editor2object(self, cleanup=None):
  1862. """
  1863. Transfers the Geometry or Excellon from it's editor to the current object.
  1864. :return: None
  1865. """
  1866. self.defaults.report_usage("editor2object()")
  1867. # re-enable the objects menu that was disabled on entry in Editor mode
  1868. self.ui.menuobjects.setDisabled(False)
  1869. # do not update a geometry or excellon object unless it comes out of an editor
  1870. if self.call_source != 'app':
  1871. edited_obj = self.collection.get_active()
  1872. if cleanup is None:
  1873. msgbox = QtWidgets.QMessageBox()
  1874. msgbox.setText(_("Do you want to save the edited object?"))
  1875. msgbox.setWindowTitle(_("Close Editor"))
  1876. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1877. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1878. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1879. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1880. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1881. msgbox.setDefaultButton(bt_yes)
  1882. msgbox.exec_()
  1883. response = msgbox.clickedButton()
  1884. if response == bt_yes:
  1885. # show the Tools Toolbar
  1886. tools_tb = self.ui.toolbartools
  1887. if self.old_state_of_tools_toolbar is True:
  1888. tools_tb.show()
  1889. # clean the Tools Tab
  1890. self.ui.tool_scroll_area.takeWidget()
  1891. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1892. self.ui.notebook.setTabText(2, _("Tool"))
  1893. if edited_obj.kind == 'geometry':
  1894. obj_type = "Geometry"
  1895. self.geo_editor.update_fcgeometry(edited_obj)
  1896. # self.geo_editor.update_options(edited_obj)
  1897. # restore GUI to the Selected TAB
  1898. # Remove anything else in the appGUI
  1899. self.ui.tool_scroll_area.takeWidget()
  1900. # update the geo object options so it is including the bounding box values
  1901. try:
  1902. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1903. edited_obj.options['xmin'] = xmin
  1904. edited_obj.options['ymin'] = ymin
  1905. edited_obj.options['xmax'] = xmax
  1906. edited_obj.options['ymax'] = ymax
  1907. except AttributeError as e:
  1908. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1909. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1910. edited_obj.build_ui()
  1911. edited_obj.plot()
  1912. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1913. elif edited_obj.kind == 'gerber':
  1914. obj_type = "Gerber"
  1915. self.grb_editor.update_fcgerber()
  1916. # self.grb_editor.update_options(edited_obj)
  1917. # delete the old object (the source object) if it was an empty one
  1918. try:
  1919. if len(edited_obj.solid_geometry) == 0:
  1920. old_name = edited_obj.options['name']
  1921. self.collection.delete_by_name(old_name)
  1922. except TypeError:
  1923. # if the solid_geometry is a single Polygon the len() will not work
  1924. # in any case, falling here means that we have something in the solid_geometry, even if only
  1925. # a single Polygon, therefore we pass this
  1926. pass
  1927. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1928. # restore GUI to the Selected TAB
  1929. # Remove anything else in the GUI
  1930. self.ui.properties_scroll_area.takeWidget()
  1931. elif edited_obj.kind == 'excellon':
  1932. obj_type = "Excellon"
  1933. self.exc_editor.update_fcexcellon(edited_obj)
  1934. # self.exc_editor.update_options(edited_obj)
  1935. # restore GUI to the Selected TAB
  1936. # Remove anything else in the GUI
  1937. self.ui.tool_scroll_area.takeWidget()
  1938. # delete the old object (the source object) if it was an empty one
  1939. # find if we have drills:
  1940. has_drills = None
  1941. for tt in edited_obj.tools:
  1942. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1943. has_drills = True
  1944. break
  1945. # find if we have slots:
  1946. has_slots = None
  1947. for tt in edited_obj.tools:
  1948. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1949. has_slots = True
  1950. break
  1951. if has_drills is None and has_slots is None:
  1952. old_name = edited_obj.options['name']
  1953. self.collection.delete_by_name(name=old_name)
  1954. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1955. elif edited_obj.kind == 'cncjob':
  1956. obj_type = "CNCJob"
  1957. self.gcode_editor.update_fcgcode(edited_obj)
  1958. # self.exc_editor.update_options(edited_obj)
  1959. # restore GUI to the Selected TAB
  1960. # Remove anything else in the GUI
  1961. self.ui.tool_scroll_area.takeWidget()
  1962. edited_obj.build_ui()
  1963. # close the open tab
  1964. for idx in range(self.ui.plot_tab_area.count()):
  1965. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1966. self.ui.plot_tab_area.closeTab(idx)
  1967. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1968. else:
  1969. self.inform.emit('[WARNING_NOTCL] %s' %
  1970. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1971. return
  1972. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1973. elif response == bt_no:
  1974. # show the Tools Toolbar
  1975. tools_tb = self.ui.toolbartools
  1976. if self.old_state_of_tools_toolbar is True:
  1977. tools_tb.show()
  1978. # clean the Tools Tab
  1979. self.ui.tool_scroll_area.takeWidget()
  1980. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1981. self.ui.notebook.setTabText(2, _("Tool"))
  1982. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1983. if edited_obj.kind == 'geometry':
  1984. self.geo_editor.deactivate()
  1985. edited_obj.build_ui()
  1986. edited_obj.plot()
  1987. elif edited_obj.kind == 'gerber':
  1988. self.grb_editor.deactivate_grb_editor()
  1989. edited_obj.build_ui()
  1990. elif edited_obj.kind == 'excellon':
  1991. self.exc_editor.deactivate()
  1992. edited_obj.build_ui()
  1993. elif edited_obj.kind == 'cncjob':
  1994. self.gcode_editor.deactivate()
  1995. edited_obj.build_ui()
  1996. # close the open tab
  1997. for idx in range(self.ui.plot_tab_area.count()):
  1998. try:
  1999. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2000. self.ui.plot_tab_area.closeTab(idx)
  2001. except AttributeError:
  2002. continue
  2003. else:
  2004. self.inform.emit('[WARNING_NOTCL] %s' %
  2005. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2006. return
  2007. elif response == bt_cancel:
  2008. return
  2009. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2010. # edited_obj.build_ui()
  2011. # Switch notebook to Properties page
  2012. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2013. else:
  2014. # show the Tools Toolbar
  2015. tools_tb = self.ui.toolbartools
  2016. if self.old_state_of_tools_toolbar is True:
  2017. tools_tb.show()
  2018. if isinstance(edited_obj, GeometryObject):
  2019. self.geo_editor.deactivate()
  2020. elif isinstance(edited_obj, GerberObject):
  2021. self.grb_editor.deactivate_grb_editor()
  2022. elif isinstance(edited_obj, ExcellonObject):
  2023. self.exc_editor.deactivate()
  2024. else:
  2025. self.inform.emit('[WARNING_NOTCL] %s' %
  2026. _("Select a Gerber, Geometry or Excellon Object to update."))
  2027. return
  2028. # if notebook is hidden we show it
  2029. if self.ui.splitter.sizes()[0] == 0:
  2030. self.ui.splitter.setSizes([1, 1])
  2031. # restore the call_source to app
  2032. self.call_source = 'app'
  2033. # edited_obj.plot()
  2034. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2035. self.ui.plot_tab_area.protectTab(0)
  2036. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2037. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2038. self.ui.project_frame.setDisabled(False)
  2039. def get_last_folder(self):
  2040. """
  2041. Get the folder path from where the last file was opened.
  2042. :return: String, last opened folder path
  2043. """
  2044. return self.defaults["global_last_folder"]
  2045. def get_last_save_folder(self):
  2046. """
  2047. Get the folder path from where the last file was saved.
  2048. :return: String, last saved folder path
  2049. """
  2050. loc = self.defaults["global_last_save_folder"]
  2051. if loc is None:
  2052. loc = self.defaults["global_last_folder"]
  2053. if loc is None:
  2054. loc = os.path.dirname(__file__)
  2055. return loc
  2056. @QtCore.pyqtSlot(str)
  2057. @QtCore.pyqtSlot(str, bool)
  2058. def info(self, msg, shell_echo=True):
  2059. """
  2060. Informs the user. Normally on the status bar, optionally
  2061. also on the shell.
  2062. :param msg: Text to write.
  2063. :type msg: str
  2064. :param shell_echo: Control if to display the message msg in the Shell
  2065. :type shell_echo: bool
  2066. :return: None
  2067. """
  2068. # Type of message in brackets at the beginning of the message.
  2069. match = re.search(r"\[(.*)\](.*)", msg)
  2070. if match:
  2071. level = match.group(1)
  2072. msg_ = match.group(2)
  2073. self.ui.fcinfo.set_status(str(msg_), level=level)
  2074. if shell_echo is True:
  2075. if level.lower() == "error":
  2076. self.shell_message(msg, error=True, show=True)
  2077. elif level.lower() == "warning":
  2078. self.shell_message(msg, warning=True, show=True)
  2079. elif level.lower() == "error_notcl":
  2080. self.shell_message(msg, error=True, show=False)
  2081. elif level.lower() == "warning_notcl":
  2082. self.shell_message(msg, warning=True, show=False)
  2083. elif level.lower() == "success":
  2084. self.shell_message(msg, success=True, show=False)
  2085. elif level.lower() == "selected":
  2086. self.shell_message(msg, selected=True, show=False)
  2087. else:
  2088. self.shell_message(msg, show=False)
  2089. else:
  2090. self.ui.fcinfo.set_status(str(msg), level="info")
  2091. # make sure that if the message is to clear the infobar with a space
  2092. # is not printed over and over on the shell
  2093. if msg != '' and shell_echo is True:
  2094. self.shell_message(msg)
  2095. def info_shell(self, msg, new_line=True):
  2096. self.shell_message(msg=msg, new_line=new_line)
  2097. def save_to_file(self, content_to_save, txt_content):
  2098. """
  2099. Save something to a file.
  2100. :return: None
  2101. """
  2102. self.defaults.report_usage("save_to_file")
  2103. App.log.debug("save_to_file()")
  2104. self.date = str(datetime.today()).rpartition('.')[0]
  2105. self.date = ''.join(c for c in self.date if c not in ':-')
  2106. self.date = self.date.replace(' ', '_')
  2107. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2108. path_to_save = self.defaults["global_last_save_folder"] if \
  2109. self.defaults["global_last_save_folder"] is not None else self.data_path
  2110. try:
  2111. filename, _f = FCFileSaveDialog.get_saved_filename(
  2112. caption=_("Save to file"),
  2113. directory=path_to_save + '/file_' + self.date,
  2114. ext_filter=filter__
  2115. )
  2116. except TypeError:
  2117. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2118. filename = str(filename)
  2119. if filename == "":
  2120. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2121. return
  2122. else:
  2123. try:
  2124. with open(filename, 'w') as f:
  2125. ___ = f.read()
  2126. except PermissionError:
  2127. self.inform.emit('[WARNING] %s' %
  2128. _("Permission denied, saving not possible.\n"
  2129. "Most likely another app is holding the file open and not accessible."))
  2130. return
  2131. except IOError:
  2132. App.log.debug('Creating a new file ...')
  2133. f = open(filename, 'w')
  2134. f.close()
  2135. except Exception:
  2136. e = sys.exc_info()[0]
  2137. App.log.error("Could not load the file.")
  2138. App.log.error(str(e))
  2139. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2140. return
  2141. # Save content
  2142. if filename.rpartition('.')[2].lower() == 'html':
  2143. file_content = content_to_save
  2144. else:
  2145. file_content = txt_content
  2146. try:
  2147. with open(filename, "w") as f:
  2148. f.write(file_content)
  2149. except Exception:
  2150. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2151. return
  2152. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2153. def register_recent(self, kind, filename):
  2154. """
  2155. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2156. dictionary.
  2157. :param kind: type of file that was opened
  2158. :param filename: the path and file name for the file that was opened
  2159. :return:
  2160. """
  2161. self.log.debug("register_recent()")
  2162. self.log.debug(" %s" % kind)
  2163. self.log.debug(" %s" % filename)
  2164. record = {'kind': str(kind), 'filename': str(filename)}
  2165. if record in self.recent:
  2166. return
  2167. if record in self.recent_projects:
  2168. return
  2169. if record['kind'] == 'project':
  2170. self.recent_projects.insert(0, record)
  2171. else:
  2172. self.recent.insert(0, record)
  2173. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2174. self.recent.pop()
  2175. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2176. self.recent_projects.pop()
  2177. try:
  2178. f = open(self.data_path + '/recent.json', 'w')
  2179. except IOError:
  2180. App.log.error("Failed to open recent items file for writing.")
  2181. self.inform.emit('[ERROR_NOTCL] %s' %
  2182. _('Failed to open recent files file for writing.'))
  2183. return
  2184. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2185. f.close()
  2186. try:
  2187. fp = open(self.data_path + '/recent_projects.json', 'w')
  2188. except IOError:
  2189. App.log.error("Failed to open recent items file for writing.")
  2190. self.inform.emit('[ERROR_NOTCL] %s' %
  2191. _('Failed to open recent projects file for writing.'))
  2192. return
  2193. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2194. fp.close()
  2195. # Re-build the recent items menu
  2196. self.setup_recent_items()
  2197. def on_about(self):
  2198. """
  2199. Displays the "about" dialog found in the Menu --> Help.
  2200. :return: None
  2201. """
  2202. self.defaults.report_usage("on_about")
  2203. version = self.version
  2204. version_date = self.version_date
  2205. beta = self.beta
  2206. class AboutDialog(QtWidgets.QDialog):
  2207. def __init__(self, app, parent=None):
  2208. QtWidgets.QDialog.__init__(self, parent)
  2209. self.app = app
  2210. # Icon and title
  2211. self.setWindowIcon(parent.app_icon)
  2212. self.setWindowTitle(_("About FlatCAM"))
  2213. self.resize(600, 200)
  2214. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2215. # self.setStyleSheet(
  2216. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2217. # "background-attachment: fixed"
  2218. # )
  2219. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2220. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2221. # palette = QtGui.QPalette()
  2222. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2223. # self.setPalette(palette)
  2224. logo = QtWidgets.QLabel()
  2225. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2226. title = QtWidgets.QLabel(
  2227. "<font size=8><B>FlatCAM</B></font><BR>"
  2228. "{title}<BR>"
  2229. "<BR>"
  2230. "<BR>"
  2231. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2232. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2233. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2234. "<B>{issue}</B></a><BR>".format(
  2235. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2236. devel=_("Development"),
  2237. down=_("DOWNLOAD"),
  2238. issue=_("Issue tracker"))
  2239. )
  2240. title.setOpenExternalLinks(True)
  2241. closebtn = QtWidgets.QPushButton(_("Close"))
  2242. tab_widget = QtWidgets.QTabWidget()
  2243. description_label = QtWidgets.QLabel(
  2244. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2245. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2246. version=version,
  2247. beta=('BETA' if beta else ''),
  2248. date=version_date,
  2249. arch=platform.architecture()[0])
  2250. )
  2251. description_label.setOpenExternalLinks(True)
  2252. lic_lbl_header = QtWidgets.QLabel(
  2253. '%s:<br>%s<br>' % (
  2254. _('Licensed under the MIT license'),
  2255. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2256. "http://www.opensource.org/licenses/mit-license.php</a>"
  2257. )
  2258. )
  2259. lic_lbl_header.setOpenExternalLinks(True)
  2260. lic_lbl_body = QtWidgets.QLabel(
  2261. _(
  2262. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2263. 'of this software and associated documentation files (the "Software"), to deal\n'
  2264. 'in the Software without restriction, including without limitation the rights\n'
  2265. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2266. 'copies of the Software, and to permit persons to whom the Software is\n'
  2267. 'furnished to do so, subject to the following conditions:\n\n'
  2268. 'The above copyright notice and this permission notice shall be included in\n'
  2269. 'all copies or substantial portions of the Software.\n\n'
  2270. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2271. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2272. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2273. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2274. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2275. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2276. 'THE SOFTWARE.'
  2277. )
  2278. )
  2279. attributions_label = QtWidgets.QLabel(
  2280. _(
  2281. 'Some of the icons used are from the following sources:<br>'
  2282. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2283. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2284. 'title="Flaticon">www.flaticon.com</a></div>'
  2285. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2286. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2287. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2288. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2289. 'title="Flaticon">www.flaticon.com</a></div>'
  2290. )
  2291. )
  2292. attributions_label.setOpenExternalLinks(True)
  2293. # layouts
  2294. layout1 = QtWidgets.QVBoxLayout()
  2295. layout1_1 = QtWidgets.QHBoxLayout()
  2296. layout1_2 = QtWidgets.QHBoxLayout()
  2297. layout2 = QtWidgets.QHBoxLayout()
  2298. layout3 = QtWidgets.QHBoxLayout()
  2299. self.setLayout(layout1)
  2300. layout1.addLayout(layout1_1)
  2301. layout1.addLayout(layout1_2)
  2302. layout1.addLayout(layout2)
  2303. layout1.addLayout(layout3)
  2304. layout1_1.addStretch()
  2305. layout1_1.addWidget(description_label)
  2306. layout1_2.addWidget(tab_widget)
  2307. self.splash_tab = QtWidgets.QWidget()
  2308. self.splash_tab.setObjectName("splash_about")
  2309. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2310. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2311. tab_widget.addTab(self.splash_tab, _("Splash"))
  2312. self.programmmers_tab = QtWidgets.QWidget()
  2313. self.programmmers_tab.setObjectName("programmers_about")
  2314. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2315. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2316. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2317. self.translators_tab = QtWidgets.QWidget()
  2318. self.translators_tab.setObjectName("translators_about")
  2319. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2320. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2321. tab_widget.addTab(self.translators_tab, _("Translators"))
  2322. self.license_tab = QtWidgets.QWidget()
  2323. self.license_tab.setObjectName("license_about")
  2324. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2325. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2326. tab_widget.addTab(self.license_tab, _("License"))
  2327. self.attributions_tab = QtWidgets.QWidget()
  2328. self.attributions_tab.setObjectName("attributions_about")
  2329. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2330. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2331. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2332. self.splash_tab_layout.addWidget(logo, stretch=0)
  2333. self.splash_tab_layout.addWidget(title, stretch=1)
  2334. pal = QtGui.QPalette()
  2335. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2336. self.prog_grid_lay = QtWidgets.QGridLayout()
  2337. self.prog_grid_lay.setHorizontalSpacing(20)
  2338. self.prog_grid_lay.setColumnStretch(0, 0)
  2339. self.prog_grid_lay.setColumnStretch(2, 1)
  2340. prog_widget = QtWidgets.QWidget()
  2341. prog_widget.setLayout(self.prog_grid_lay)
  2342. prog_scroll = QtWidgets.QScrollArea()
  2343. prog_scroll.setWidget(prog_widget)
  2344. prog_scroll.setWidgetResizable(True)
  2345. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2346. prog_scroll.setPalette(pal)
  2347. self.programmmers_tab_layout.addWidget(prog_scroll)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2395. self.translator_grid_lay = QtWidgets.QGridLayout()
  2396. self.translator_grid_lay.setColumnStretch(0, 0)
  2397. self.translator_grid_lay.setColumnStretch(1, 0)
  2398. self.translator_grid_lay.setColumnStretch(2, 1)
  2399. self.translator_grid_lay.setColumnStretch(3, 0)
  2400. # trans_widget = QtWidgets.QWidget()
  2401. # trans_widget.setLayout(self.translator_grid_lay)
  2402. # self.translators_tab_layout.addWidget(trans_widget)
  2403. # self.translators_tab_layout.addStretch()
  2404. trans_widget = QtWidgets.QWidget()
  2405. trans_widget.setLayout(self.translator_grid_lay)
  2406. trans_scroll = QtWidgets.QScrollArea()
  2407. trans_scroll.setWidget(trans_widget)
  2408. trans_scroll.setWidgetResizable(True)
  2409. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2410. trans_scroll.setPalette(pal)
  2411. self.translators_tab_layout.addWidget(trans_scroll)
  2412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2423. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2424. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2425. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2426. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2430. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2448. self.translator_grid_lay.setColumnStretch(0, 0)
  2449. self.translators_tab_layout.addStretch()
  2450. self.license_tab_layout.addWidget(lic_lbl_header)
  2451. self.license_tab_layout.addWidget(lic_lbl_body)
  2452. self.license_tab_layout.addStretch()
  2453. self.attributions_tab_layout.addWidget(attributions_label)
  2454. self.attributions_tab_layout.addStretch()
  2455. layout3.addStretch()
  2456. layout3.addWidget(closebtn)
  2457. closebtn.clicked.connect(self.accept)
  2458. AboutDialog(app=self, parent=self.ui).exec_()
  2459. def on_readme(self):
  2460. """
  2461. Displays the "about" dialog found in the Menu --> Help.
  2462. :return: None
  2463. """
  2464. class ReadmeDialog(QtWidgets.QDialog):
  2465. def __init__(self, app, parent=None):
  2466. QtWidgets.QDialog.__init__(self, parent)
  2467. self.app = app
  2468. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2469. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2470. "<b>click</b></a>"
  2471. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2472. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2473. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2474. # Icon and title
  2475. self.setWindowIcon(parent.app_icon)
  2476. self.setWindowTitle(_("Important Information's"))
  2477. self.resize(750, 375)
  2478. logo = QtWidgets.QLabel()
  2479. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2480. # content = QtWidgets.QLabel(
  2481. # "%s<br>"
  2482. # "%s<br><br>"
  2483. # "%s,<br>"
  2484. # "%s<br>"
  2485. # "<ul>"
  2486. # "<li> &nbsp;%s %s</li>"
  2487. # "<li> &nbsp;%s %s</li>"
  2488. # "</ul>"
  2489. # "%s %s.<br>"
  2490. # "%s"
  2491. # "<ul>"
  2492. # "<li> &nbsp;%s &#128077;</li>"
  2493. # "<li> &nbsp;%s &#128513;</li>"
  2494. # "</ul>" %
  2495. # (
  2496. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2497. # _("Yet it cannot evolve without <b>contributions</b>."),
  2498. # _("If you want to see this application grow and become better and better"),
  2499. # _("you can <b>contribute</b> to the development yourself by:"),
  2500. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2501. # new_features_link,
  2502. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2503. # bugs_link,
  2504. # _("If you like or use this program you can make a donation"),
  2505. # donation_link,
  2506. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2507. # _("it will be welcomed with joy"),
  2508. # _("it will give me a reason to continue")
  2509. # )
  2510. # )
  2511. content = QtWidgets.QLabel(
  2512. "%s<br>"
  2513. "%s<br><br>"
  2514. "%s,<br>"
  2515. "%s<br>"
  2516. "<ul>"
  2517. "<li> &nbsp;%s %s</li>"
  2518. "<li> &nbsp;%s %s</li>"
  2519. "</ul>" %
  2520. (
  2521. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2522. _("Yet it cannot evolve without <b>contributions</b>."),
  2523. _("If you want to see this application grow and become better and better"),
  2524. _("you can <b>contribute</b> to the development yourself by:"),
  2525. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2526. new_features_link,
  2527. _("Bug Reports by providing the steps required to reproduce the bug"),
  2528. bugs_link
  2529. )
  2530. )
  2531. content.setOpenExternalLinks(True)
  2532. # palette
  2533. pal = QtGui.QPalette()
  2534. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2535. # layouts
  2536. main_layout = QtWidgets.QVBoxLayout()
  2537. self.setLayout(main_layout)
  2538. tab_layout = QtWidgets.QHBoxLayout()
  2539. buttons_hlay = QtWidgets.QHBoxLayout()
  2540. main_layout.addLayout(tab_layout)
  2541. main_layout.addLayout(buttons_hlay)
  2542. tab_widget = QtWidgets.QTabWidget()
  2543. tab_layout.addWidget(tab_widget)
  2544. closebtn = QtWidgets.QPushButton(_("Close"))
  2545. buttons_hlay.addStretch()
  2546. buttons_hlay.addWidget(closebtn)
  2547. # CONTRIBUTE section
  2548. self.intro_tab = QtWidgets.QWidget()
  2549. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2550. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2551. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2552. self.grid_lay = QtWidgets.QGridLayout()
  2553. self.grid_lay.setHorizontalSpacing(20)
  2554. self.grid_lay.setColumnStretch(0, 0)
  2555. self.grid_lay.setColumnStretch(1, 1)
  2556. intro_wdg = QtWidgets.QWidget()
  2557. intro_wdg.setLayout(self.grid_lay)
  2558. intro_scroll_area = QtWidgets.QScrollArea()
  2559. intro_scroll_area.setWidget(intro_wdg)
  2560. intro_scroll_area.setWidgetResizable(True)
  2561. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2562. intro_scroll_area.setPalette(pal)
  2563. self.grid_lay.addWidget(logo, 0, 0)
  2564. self.grid_lay.addWidget(content, 0, 1)
  2565. self.intro_tab_layout.addWidget(intro_scroll_area)
  2566. # LINKS EXCHANGE section
  2567. self.links_tab = QtWidgets.QWidget()
  2568. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2569. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2570. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2571. self.links_lay = QtWidgets.QHBoxLayout()
  2572. links_wdg = QtWidgets.QWidget()
  2573. links_wdg.setLayout(self.links_lay)
  2574. links_scroll_area = QtWidgets.QScrollArea()
  2575. links_scroll_area.setWidget(links_wdg)
  2576. links_scroll_area.setWidgetResizable(True)
  2577. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2578. links_scroll_area.setPalette(pal)
  2579. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2580. self.links_tab_layout.addWidget(links_scroll_area)
  2581. # HOW TO section
  2582. self.howto_tab = QtWidgets.QWidget()
  2583. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2584. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2585. tab_widget.addTab(self.howto_tab, _("How To's"))
  2586. self.howto_lay = QtWidgets.QHBoxLayout()
  2587. howto_wdg = QtWidgets.QWidget()
  2588. howto_wdg.setLayout(self.howto_lay)
  2589. howto_scroll_area = QtWidgets.QScrollArea()
  2590. howto_scroll_area.setWidget(howto_wdg)
  2591. howto_scroll_area.setWidgetResizable(True)
  2592. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2593. howto_scroll_area.setPalette(pal)
  2594. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2595. self.howto_tab_layout.addWidget(howto_scroll_area)
  2596. # BUTTONS section
  2597. closebtn.clicked.connect(self.accept)
  2598. ReadmeDialog(app=self, parent=self.ui).exec_()
  2599. def install_bookmarks(self, book_dict=None):
  2600. """
  2601. Install the bookmarks actions in the Help menu -> Bookmarks
  2602. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2603. :return: None
  2604. """
  2605. if book_dict is None:
  2606. self.defaults["global_bookmarks"].update(
  2607. {
  2608. '1': ['FlatCAM', "http://flatcam.org"],
  2609. '2': ['Backup Site', ""]
  2610. }
  2611. )
  2612. else:
  2613. self.defaults["global_bookmarks"].clear()
  2614. self.defaults["global_bookmarks"].update(book_dict)
  2615. # first try to disconnect if somehow they get connected from elsewhere
  2616. for act in self.ui.menuhelp_bookmarks.actions():
  2617. try:
  2618. act.triggered.disconnect()
  2619. except TypeError:
  2620. pass
  2621. # clear all actions except the last one who is the Bookmark manager
  2622. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2623. pass
  2624. else:
  2625. self.ui.menuhelp_bookmarks.removeAction(act)
  2626. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2627. if self.defaults["global_bookmarks"]:
  2628. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2629. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2630. # the JSON is first making the keys as strings (therefore I have to use strings too
  2631. # or do the conversion :(
  2632. # )
  2633. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2634. # the '10' entry jsut after '1' therefore ordering as strings
  2635. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2636. key=lambda x: int(x[0]))
  2637. for entry, bookmark in sorted_bookmarks:
  2638. title = bookmark[0]
  2639. weblink = bookmark[1]
  2640. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2641. act.setText(title)
  2642. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2643. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2644. if title == 'Backup Site' and weblink == "":
  2645. act.triggered.connect(self.on_backup_site)
  2646. else:
  2647. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2648. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2649. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2650. def on_bookmarks_manager(self):
  2651. """
  2652. Adds the bookmark manager in a Tab in Plot Area
  2653. :return:
  2654. """
  2655. for idx in range(self.ui.plot_tab_area.count()):
  2656. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2657. # there can be only one instance of Bookmark Manager at one time
  2658. return
  2659. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2660. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2661. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2662. # add the tab if it was closed
  2663. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2664. # delete the absolute and relative position and messages in the infobar
  2665. # self.ui.position_label.setText("")
  2666. # self.ui.rel_position_label.setText("")
  2667. # hide coordinates toolbars in the infobar while in DB
  2668. self.ui.coords_toolbar.hide()
  2669. self.ui.delta_coords_toolbar.hide()
  2670. # Switch plot_area to preferences page
  2671. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2672. def on_backup_site(self):
  2673. msgbox = QtWidgets.QMessageBox()
  2674. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2675. "1. FlatCAM.org website is down\n"
  2676. "2. Someone forked FlatCAM project and wants to point\n"
  2677. "to his own website\n\n"
  2678. "If you can't get any informations about FlatCAM beta\n"
  2679. "use the YouTube channel link from the Help menu."))
  2680. msgbox.setWindowTitle(_("Alternative website"))
  2681. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2682. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2683. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2684. msgbox.setDefaultButton(bt_yes)
  2685. msgbox.exec_()
  2686. # response = msgbox.clickedButton()
  2687. def final_save(self):
  2688. """
  2689. Callback for doing a preferences save to file whenever the application is about to quit.
  2690. If the project has changes, it will ask the user to save the project.
  2691. :return: None
  2692. """
  2693. if self.save_in_progress:
  2694. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2695. return
  2696. if self.should_we_save and self.collection.get_list():
  2697. msgbox = QtWidgets.QMessageBox()
  2698. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2699. "\n"
  2700. "Do you want to Save the project?"))
  2701. msgbox.setWindowTitle(_("Save changes"))
  2702. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2703. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2704. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2705. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2706. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2707. msgbox.setDefaultButton(bt_yes)
  2708. msgbox.exec_()
  2709. response = msgbox.clickedButton()
  2710. if response == bt_yes:
  2711. try:
  2712. self.trayIcon.hide()
  2713. except Exception:
  2714. pass
  2715. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2716. elif response == bt_no:
  2717. try:
  2718. self.trayIcon.hide()
  2719. except Exception:
  2720. pass
  2721. self.quit_application()
  2722. elif response == bt_cancel:
  2723. return
  2724. else:
  2725. try:
  2726. self.trayIcon.hide()
  2727. except Exception:
  2728. pass
  2729. self.quit_application()
  2730. def quit_application(self):
  2731. """
  2732. Called (as a pyslot or not) when the application is quit.
  2733. :return: None
  2734. """
  2735. # close editors before quiting the app, if they are open
  2736. if self.geo_editor.editor_active is True:
  2737. self.geo_editor.deactivate()
  2738. try:
  2739. self.geo_editor.disconnect()
  2740. except TypeError:
  2741. pass
  2742. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2743. if self.exc_editor.editor_active is True:
  2744. self.exc_editor.deactivate()
  2745. try:
  2746. self.grb_editor.disconnect()
  2747. except TypeError:
  2748. pass
  2749. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2750. if self.grb_editor.editor_active is True:
  2751. self.grb_editor.deactivate_grb_editor()
  2752. try:
  2753. self.exc_editor.disconnect()
  2754. except TypeError:
  2755. pass
  2756. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2757. # disconnect the mouse events
  2758. if self.is_legacy:
  2759. self.plotcanvas.graph_event_disconnect(self.mm)
  2760. self.plotcanvas.graph_event_disconnect(self.mp)
  2761. self.plotcanvas.graph_event_disconnect(self.mr)
  2762. self.plotcanvas.graph_event_disconnect(self.mdc)
  2763. self.plotcanvas.graph_event_disconnect(self.kp)
  2764. else:
  2765. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2766. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2767. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2768. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2769. self.on_mouse_double_click_over_plot)
  2770. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2771. self.preferencesUiManager.save_defaults(silent=True)
  2772. log.debug("App.quit_application() --> App Defaults saved.")
  2773. if self.cmd_line_headless != 1:
  2774. # save app state to file
  2775. stgs = QSettings("Open Source", "FlatCAM")
  2776. stgs.setValue('saved_gui_state', self.ui.saveState())
  2777. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2778. stgs.setValue(
  2779. 'language',
  2780. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2781. )
  2782. stgs.setValue(
  2783. 'notebook_font_size',
  2784. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2785. )
  2786. stgs.setValue(
  2787. 'axis_font_size',
  2788. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2789. )
  2790. stgs.setValue(
  2791. 'textbox_font_size',
  2792. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2793. )
  2794. stgs.setValue(
  2795. 'hud_font_size',
  2796. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2797. )
  2798. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2799. stgs.setValue(
  2800. 'machinist',
  2801. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2802. )
  2803. # This will write the setting to the platform specific storage.
  2804. del stgs
  2805. log.debug("App.quit_application() --> App UI state saved.")
  2806. # try to quit the Socket opened by ArgsThread class
  2807. try:
  2808. # self.new_launch.thread_exit = True
  2809. # self.new_launch.listener.close()
  2810. self.new_launch.stop.emit()
  2811. except Exception as err:
  2812. log.debug("App.quit_application() --> %s" % str(err))
  2813. # try to quit the QThread that run ArgsThread class
  2814. try:
  2815. # del self.new_launch
  2816. self.listen_th.quit()
  2817. except Exception as e:
  2818. log.debug("App.quit_application() --> %s" % str(e))
  2819. # terminate workers
  2820. # self.workers.__del__()
  2821. self.clear_pool()
  2822. # quit app by signalling for self.kill_app() method
  2823. # self.close_app_signal.emit()
  2824. QtWidgets.qApp.quit()
  2825. sys.exit(0)
  2826. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2827. # we use the following command
  2828. # minor_v = sys.version_info.minor
  2829. # if minor_v < 8:
  2830. # # make sure that the app closes
  2831. # sys.exit(0)
  2832. # else:
  2833. # os._exit(0) # fix to work with Python 3.8
  2834. @staticmethod
  2835. def kill_app():
  2836. QtWidgets.qApp.quit()
  2837. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2838. # we use the following command
  2839. sys.exit(0)
  2840. def on_portable_checked(self, state):
  2841. """
  2842. Callback called when the checkbox in Preferences GUI is checked.
  2843. It will set the application as portable by creating the preferences and recent files in the
  2844. 'config' folder found in the FlatCAM installation folder.
  2845. :param state: boolean, the state of the checkbox when clicked/checked
  2846. :return:
  2847. """
  2848. line_no = 0
  2849. data = None
  2850. if sys.platform != 'win32':
  2851. # this won't work in Linux or MacOS
  2852. return
  2853. # test if the app was frozen and choose the path for the configuration file
  2854. if getattr(sys, "frozen", False) is True:
  2855. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2856. else:
  2857. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2858. config_file = current_data_path + '\\configuration.txt'
  2859. try:
  2860. with open(config_file, 'r') as f:
  2861. try:
  2862. data = f.readlines()
  2863. except Exception as e:
  2864. log.debug('App.__init__() -->%s' % str(e))
  2865. return
  2866. except FileNotFoundError:
  2867. pass
  2868. for line in data:
  2869. line = line.strip('\n')
  2870. param = str(line).rpartition('=')
  2871. if param[0] == 'portable':
  2872. break
  2873. line_no += 1
  2874. if state:
  2875. data[line_no] = 'portable=True\n'
  2876. # create the new defauults files
  2877. # create current_defaults.FlatConfig file if there is none
  2878. try:
  2879. f = open(current_data_path + '/current_defaults.FlatConfig')
  2880. f.close()
  2881. except IOError:
  2882. App.log.debug('Creating empty current_defaults.FlatConfig')
  2883. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2884. json.dump({}, f)
  2885. f.close()
  2886. # create factory_defaults.FlatConfig file if there is none
  2887. try:
  2888. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2889. f.close()
  2890. except IOError:
  2891. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2892. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2893. json.dump({}, f)
  2894. f.close()
  2895. try:
  2896. f = open(current_data_path + '/recent.json')
  2897. f.close()
  2898. except IOError:
  2899. App.log.debug('Creating empty recent.json')
  2900. f = open(current_data_path + '/recent.json', 'w')
  2901. json.dump([], f)
  2902. f.close()
  2903. try:
  2904. fp = open(current_data_path + '/recent_projects.json')
  2905. fp.close()
  2906. except IOError:
  2907. App.log.debug('Creating empty recent_projects.json')
  2908. fp = open(current_data_path + '/recent_projects.json', 'w')
  2909. json.dump([], fp)
  2910. fp.close()
  2911. # save the current defaults to the new defaults file
  2912. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2913. else:
  2914. data[line_no] = 'portable=False\n'
  2915. with open(config_file, 'w') as f:
  2916. f.writelines(data)
  2917. def on_register_files(self, obj_type=None):
  2918. """
  2919. Called whenever there is a need to register file extensions with FlatCAM.
  2920. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2921. :param obj_type: the type of object to be register for.
  2922. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2923. :return: None
  2924. """
  2925. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2926. new_reg_path = 'Software\\Classes\\'
  2927. # find if the current user is admin
  2928. try:
  2929. is_admin = os.getuid() == 0
  2930. except AttributeError:
  2931. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2932. if is_admin is True:
  2933. root_path = winreg.HKEY_LOCAL_MACHINE
  2934. else:
  2935. root_path = winreg.HKEY_CURRENT_USER
  2936. # create the keys
  2937. def set_reg(name, root_pth, new_reg_path, value):
  2938. try:
  2939. winreg.CreateKey(root_pth, new_reg_path)
  2940. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2941. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2942. return True
  2943. except WindowsError:
  2944. return False
  2945. # delete key in registry
  2946. def delete_reg(root_pth, reg_path, key_to_del):
  2947. key_to_del_path = reg_path + key_to_del
  2948. try:
  2949. winreg.DeleteKey(root_pth, key_to_del_path)
  2950. return True
  2951. except WindowsError:
  2952. return False
  2953. if obj_type is None or obj_type == 'excellon':
  2954. exc_list = \
  2955. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2956. exc_list = [x for x in exc_list if x != '']
  2957. # register all keys in the Preferences window
  2958. for ext in exc_list:
  2959. new_k = new_reg_path + '.%s' % ext
  2960. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2961. # and unregister those that are no longer in the Preferences windows but are in the file
  2962. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2963. if ext not in exc_list:
  2964. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2965. # now write the updated extensions to the self.defaults
  2966. # new_ext = ''
  2967. # for ext in exc_list:
  2968. # new_ext = new_ext + ext + ', '
  2969. # self.defaults["fa_excellon"] = new_ext
  2970. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2971. if obj_type is None or obj_type == 'gcode':
  2972. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2973. gco_list = [x for x in gco_list if x != '']
  2974. # register all keys in the Preferences window
  2975. for ext in gco_list:
  2976. new_k = new_reg_path + '.%s' % ext
  2977. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2978. # and unregister those that are no longer in the Preferences windows but are in the file
  2979. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2980. if ext not in gco_list:
  2981. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2982. # now write the updated extensions to the self.defaults
  2983. # new_ext = ''
  2984. # for ext in gco_list:
  2985. # new_ext = new_ext + ext + ', '
  2986. # self.defaults["fa_gcode"] = new_ext
  2987. self.inform.emit('[success] %s' %
  2988. _("Selected GCode file extensions registered with FlatCAM."))
  2989. if obj_type is None or obj_type == 'gerber':
  2990. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2991. grb_list = [x for x in grb_list if x != '']
  2992. # register all keys in the Preferences window
  2993. for ext in grb_list:
  2994. new_k = new_reg_path + '.%s' % ext
  2995. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2996. # and unregister those that are no longer in the Preferences windows but are in the file
  2997. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2998. if ext not in grb_list:
  2999. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3000. # now write the updated extensions to the self.defaults
  3001. # new_ext = ''
  3002. # for ext in grb_list:
  3003. # new_ext = new_ext + ext + ', '
  3004. # self.defaults["fa_gerber"] = new_ext
  3005. self.inform.emit('[success] %s' %
  3006. _("Selected Gerber file extensions registered with FlatCAM."))
  3007. def add_extension(self, ext_type):
  3008. """
  3009. Add a file extension to the list for a specific object
  3010. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3011. :return:
  3012. """
  3013. if ext_type == 'excellon':
  3014. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3015. if new_ext == '':
  3016. return
  3017. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3018. if new_ext in old_val:
  3019. return
  3020. old_val.append(new_ext)
  3021. old_val.sort()
  3022. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3023. if ext_type == 'gcode':
  3024. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3025. if new_ext == '':
  3026. return
  3027. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3028. if new_ext in old_val:
  3029. return
  3030. old_val.append(new_ext)
  3031. old_val.sort()
  3032. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3033. if ext_type == 'gerber':
  3034. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3035. if new_ext == '':
  3036. return
  3037. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3038. if new_ext in old_val:
  3039. return
  3040. old_val.append(new_ext)
  3041. old_val.sort()
  3042. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3043. if ext_type == 'keyword':
  3044. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3045. if new_kw == '':
  3046. return
  3047. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3048. if new_kw in old_val:
  3049. return
  3050. old_val.append(new_kw)
  3051. old_val.sort()
  3052. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3053. # update the self.myKeywords so the model is updated
  3054. self.autocomplete_kw_list = \
  3055. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3056. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3057. self.shell._edit.set_model_data(self.myKeywords)
  3058. def del_extension(self, ext_type):
  3059. """
  3060. Remove a file extension from the list for a specific object
  3061. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3062. :return:
  3063. """
  3064. if ext_type == 'excellon':
  3065. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3066. if new_ext == '':
  3067. return
  3068. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3069. if new_ext not in old_val:
  3070. return
  3071. old_val.remove(new_ext)
  3072. old_val.sort()
  3073. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3074. if ext_type == 'gcode':
  3075. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3076. if new_ext == '':
  3077. return
  3078. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3079. if new_ext not in old_val:
  3080. return
  3081. old_val.remove(new_ext)
  3082. old_val.sort()
  3083. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3084. if ext_type == 'gerber':
  3085. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3086. if new_ext == '':
  3087. return
  3088. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3089. if new_ext not in old_val:
  3090. return
  3091. old_val.remove(new_ext)
  3092. old_val.sort()
  3093. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3094. if ext_type == 'keyword':
  3095. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3096. if new_kw == '':
  3097. return
  3098. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3099. if new_kw not in old_val:
  3100. return
  3101. old_val.remove(new_kw)
  3102. old_val.sort()
  3103. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3104. # update the self.myKeywords so the model is updated
  3105. self.autocomplete_kw_list = \
  3106. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3107. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3108. self.shell._edit.set_model_data(self.myKeywords)
  3109. def restore_extensions(self, ext_type):
  3110. """
  3111. Restore all file extensions associations with FlatCAM, for a specific object
  3112. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3113. :return:
  3114. """
  3115. if ext_type == 'excellon':
  3116. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3117. # for the ability to open Excellon files with .txt extension
  3118. new_exc_list = deepcopy(self.exc_list)
  3119. try:
  3120. new_exc_list.remove('txt')
  3121. except ValueError:
  3122. pass
  3123. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3124. if ext_type == 'gcode':
  3125. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3126. if ext_type == 'gerber':
  3127. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3128. if ext_type == 'keyword':
  3129. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3130. # update the self.myKeywords so the model is updated
  3131. self.autocomplete_kw_list = self.default_keywords
  3132. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3133. self.shell._edit.set_model_data(self.myKeywords)
  3134. def delete_all_extensions(self, ext_type):
  3135. """
  3136. Delete all file extensions associations with FlatCAM, for a specific object
  3137. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3138. :return:
  3139. """
  3140. if ext_type == 'excellon':
  3141. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3142. if ext_type == 'gcode':
  3143. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3144. if ext_type == 'gerber':
  3145. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3146. if ext_type == 'keyword':
  3147. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3148. # update the self.myKeywords so the model is updated
  3149. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3150. self.shell._edit.set_model_data(self.myKeywords)
  3151. def on_edit_join(self, name=None):
  3152. """
  3153. Callback for Edit->Join. Joins the selected geometry objects into
  3154. a new one.
  3155. :return: None
  3156. """
  3157. self.defaults.report_usage("on_edit_join()")
  3158. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3159. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3160. geo_type_set = set()
  3161. objs = self.collection.get_selected()
  3162. if len(objs) < 2:
  3163. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3164. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3165. return 'fail'
  3166. for obj in objs:
  3167. geo_type_set.add(obj.multigeo)
  3168. # if len(geo_type_list) == 1 means that all list elements are the same
  3169. if len(geo_type_set) != 1:
  3170. self.inform.emit('[ERROR] %s' %
  3171. _("Failed join. The Geometry objects are of different types.\n"
  3172. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3173. "convert from one to another and retry joining \n"
  3174. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3175. "the result may not be what was expected. \n"
  3176. "Check the generated GCODE."))
  3177. return
  3178. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3179. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3180. if True in geo_type_set:
  3181. def initialize(geo_obj, app):
  3182. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3183. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3184. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3185. for v in geo_obj.tools.values():
  3186. v['data']['name'] = obj_name_multi
  3187. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3188. else:
  3189. def initialize(geo_obj, app):
  3190. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3191. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3192. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3193. for v in geo_obj.tools.values():
  3194. v['data']['name'] = obj_name_single
  3195. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3196. self.should_we_save = True
  3197. def on_edit_join_exc(self):
  3198. """
  3199. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3200. a new Excellon.
  3201. :return: None
  3202. """
  3203. self.defaults.report_usage("on_edit_join_exc()")
  3204. objs = self.collection.get_selected()
  3205. for obj in objs:
  3206. if not isinstance(obj, ExcellonObject):
  3207. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3208. return
  3209. if len(objs) < 2:
  3210. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3211. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3212. return 'fail'
  3213. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3214. def initialize(exc_obj, app):
  3215. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3216. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3217. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3218. self.should_we_save = True
  3219. def on_edit_join_grb(self):
  3220. """
  3221. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3222. a new Gerber object.
  3223. :return: None
  3224. """
  3225. self.defaults.report_usage("on_edit_join_grb()")
  3226. objs = self.collection.get_selected()
  3227. for obj in objs:
  3228. if not isinstance(obj, GerberObject):
  3229. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3230. return
  3231. if len(objs) < 2:
  3232. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3233. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3234. return 'fail'
  3235. def initialize(grb_obj, app):
  3236. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3237. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3238. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3239. self.should_we_save = True
  3240. def on_convert_singlegeo_to_multigeo(self):
  3241. """
  3242. Called for converting a Geometry object from single-geo to multi-geo.
  3243. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3244. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3245. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3246. the solid-geometry of that tool.
  3247. :return: None
  3248. """
  3249. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3250. obj = self.collection.get_active()
  3251. if obj is None:
  3252. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3253. return
  3254. if not isinstance(obj, GeometryObject):
  3255. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3256. return
  3257. obj.multigeo = True
  3258. for tooluid, dict_value in obj.tools.items():
  3259. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3260. if not isinstance(obj.solid_geometry, list):
  3261. obj.solid_geometry = [obj.solid_geometry]
  3262. # obj.solid_geometry[:] = []
  3263. obj.plot()
  3264. self.should_we_save = True
  3265. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3266. def on_convert_multigeo_to_singlegeo(self):
  3267. """
  3268. Called for converting a Geometry object from multi-geo to single-geo.
  3269. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3270. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3271. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3272. the solid-geometry of that tool.
  3273. :return: None
  3274. """
  3275. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3276. obj = self.collection.get_active()
  3277. if obj is None:
  3278. self.inform.emit('[ERROR_NOTCL] %s' %
  3279. _("Failed. Select a Geometry Object and try again."))
  3280. return
  3281. if not isinstance(obj, GeometryObject):
  3282. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3283. (_("Expected a GeometryObject, got"), type(obj)))
  3284. return
  3285. obj.multigeo = False
  3286. total_solid_geometry = []
  3287. for tooluid, dict_value in obj.tools.items():
  3288. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3289. # clear the original geometry
  3290. dict_value['solid_geometry'][:] = []
  3291. obj.solid_geometry = deepcopy(total_solid_geometry)
  3292. obj.plot()
  3293. self.should_we_save = True
  3294. self.inform.emit('[success] %s' %
  3295. _("A Geometry object was converted to SingleGeo type."))
  3296. def on_defaults_dict_change(self, field):
  3297. """
  3298. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3299. Edit -> Preferences tab window.
  3300. :param field: the key of the self.defaults dictionary that was changed.
  3301. :return: None
  3302. """
  3303. self.preferencesUiManager.defaults_write_form_field(field=field)
  3304. if field == "units":
  3305. self.set_screen_units(self.defaults['units'])
  3306. def set_screen_units(self, units):
  3307. """
  3308. Set the FlatCAM units on the status bar.
  3309. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3310. :return: None
  3311. """
  3312. self.ui.units_label.setText("[" + units.lower() + "]")
  3313. def on_toggle_units_click(self):
  3314. try:
  3315. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3316. except (TypeError, AttributeError):
  3317. pass
  3318. if self.defaults["units"] == 'MM':
  3319. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3320. else:
  3321. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3322. self.on_toggle_units(no_pref=True)
  3323. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3324. lambda: self.on_toggle_units(no_pref=False))
  3325. def scale_defaults(self, sfactor, dimensions):
  3326. for dim in dimensions:
  3327. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3328. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3329. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3330. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3331. if not self.defaults[dim] or self.defaults[dim] == '':
  3332. continue
  3333. if isinstance(self.defaults[dim], str):
  3334. try:
  3335. tools_diameters = eval(self.defaults[dim])
  3336. except Exception as e:
  3337. log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3338. continue
  3339. elif isinstance(self.defaults[dim], (float, int)):
  3340. tools_diameters = [self.defaults[dim]]
  3341. else:
  3342. tools_diameters = list(self.defaults[dim])
  3343. if isinstance(tools_diameters, (tuple, list)):
  3344. pass
  3345. elif isinstance(tools_diameters, (int, float)):
  3346. tools_diameters = [self.defaults[dim]]
  3347. else:
  3348. continue
  3349. td_len = len(tools_diameters)
  3350. conv_list = []
  3351. for t in range(td_len):
  3352. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3353. self.defaults[dim] = conv_list
  3354. elif dim in ['global_gridx', 'global_gridy']:
  3355. # format the number of decimals to the one specified in self.decimals
  3356. try:
  3357. val = float(self.defaults[dim]) * sfactor
  3358. except Exception as e:
  3359. log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3360. continue
  3361. self.defaults[dim] = self.dec_format(val, self.decimals)
  3362. else:
  3363. # the number of decimals for the rest is kept unchanged
  3364. if self.defaults[dim]:
  3365. try:
  3366. val = float(self.defaults[dim]) * sfactor
  3367. except Exception as e:
  3368. log.debug(
  3369. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3370. )
  3371. continue
  3372. self.defaults[dim] = self.dec_format(val, self.decimals)
  3373. def on_toggle_units(self, no_pref=False):
  3374. """
  3375. Callback for the Units radio-button change in the Preferences tab.
  3376. Changes the application's default units adn for the project too.
  3377. If changing the project's units, the change propagates to all of
  3378. the objects in the project.
  3379. :return: None
  3380. """
  3381. self.defaults.report_usage("on_toggle_units")
  3382. if self.toggle_units_ignore:
  3383. return
  3384. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3385. # If option is the same, then ignore
  3386. if new_units == self.defaults["units"].upper():
  3387. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3388. return
  3389. # Keys in self.defaults for which to scale their values
  3390. dimensions = [
  3391. # Global
  3392. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3393. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3394. # Gerber Object
  3395. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3396. # Gerber Editor
  3397. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3398. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3399. # Excellon Object
  3400. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3401. # Excellon Editor
  3402. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3403. "excellon_editor_slot_length",
  3404. # Geometry Object
  3405. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3406. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3407. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3408. "geometry_extracut_length", "geometry_z_pdepth",
  3409. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3410. # CNCJob Object
  3411. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3412. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3413. # Isolation Tool
  3414. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3415. # Drilling Tool
  3416. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3417. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3418. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3419. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3420. # NCC Tool
  3421. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3422. "tools_ncc_newdia",
  3423. # Cutout Tool
  3424. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3425. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3426. # Paint Tool
  3427. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3428. # 2Sided Tool
  3429. "tools_2sided_drilldia",
  3430. # Film Tool
  3431. "tools_film_boundary", "tools_film_scale_stroke",
  3432. # Panel Tool
  3433. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3434. "tools_panelize_constrainy",
  3435. # Calculators Tool
  3436. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3437. # Transform Tool
  3438. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3439. "tools_transform_buffer_dis",
  3440. # SolderPaste Tool
  3441. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3442. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3443. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3444. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3445. # Corner Markers Tool
  3446. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3447. # Check Rules Tool
  3448. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3449. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3450. # QRCode Tool
  3451. "tools_qrcode_border_size",
  3452. # Copper Thieving Tool
  3453. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3454. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3455. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3456. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3457. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3458. "tools_copper_thieving_mask_clearance",
  3459. # Fiducials Tool
  3460. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3461. # Calibration Tool
  3462. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3463. # Drills Extraction Tool
  3464. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3465. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3466. # Punch Gerber Tool
  3467. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3468. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3469. # Invert Gerber Tool
  3470. "tools_invert_margin",
  3471. ]
  3472. # The scaling factor depending on choice of units.
  3473. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3474. # Changing project units. Warn user.
  3475. msgbox = QtWidgets.QMessageBox()
  3476. msgbox.setWindowTitle(_("Toggle Units"))
  3477. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3478. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3479. msgbox.setText(_("Changing the units of the project\n"
  3480. "will scale all objects.\n\n"
  3481. "Do you want to continue?"))
  3482. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3483. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3484. msgbox.setDefaultButton(bt_ok)
  3485. msgbox.exec_()
  3486. response = msgbox.clickedButton()
  3487. if response == bt_ok:
  3488. if no_pref is False:
  3489. self.preferencesUiManager.defaults_read_form()
  3490. self.scale_defaults(factor, dimensions)
  3491. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3492. self.defaults["units"] = new_units
  3493. # update the defaults from form, some may assume that the conversion is enough and it's not
  3494. self.on_options_app2project()
  3495. # update the objects
  3496. for obj in self.collection.get_list():
  3497. obj.convert_units(new_units)
  3498. # make that the properties stored in the object are also updated
  3499. self.app_obj.object_changed.emit(obj)
  3500. # rebuild the object UI
  3501. obj.build_ui()
  3502. # change this only if the workspace is active
  3503. if self.defaults['global_workspace'] is True:
  3504. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3505. # adjust the grid values on the main toolbar
  3506. val_x = float(self.defaults['global_gridx']) * factor
  3507. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3508. current = self.collection.get_active()
  3509. if current is not None:
  3510. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3511. if not isinstance(current, GeometryObject):
  3512. current.to_form()
  3513. # replot all objects
  3514. self.plot_all()
  3515. # set the status labels to reflect the current FlatCAM units
  3516. self.set_screen_units(new_units)
  3517. # signal to the app that we changed the object properties and it should save the project
  3518. self.should_we_save = True
  3519. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3520. else:
  3521. # Undo toggling
  3522. self.toggle_units_ignore = True
  3523. if self.defaults['units'].upper() == 'MM':
  3524. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3525. else:
  3526. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3527. self.toggle_units_ignore = False
  3528. # store the grid values so they are not changed in the next step
  3529. val_x = float(self.defaults['global_gridx'])
  3530. val_y = float(self.defaults['global_gridy'])
  3531. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3532. self.preferencesUiManager.defaults_read_form()
  3533. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3534. # in self.defaults from the GUI elements but
  3535. # I don't want it for the grid values, so I update them here
  3536. self.defaults['global_gridx'] = val_x
  3537. self.defaults['global_gridy'] = val_y
  3538. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3539. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3540. def on_deselect_all(self):
  3541. self.collection.set_all_inactive()
  3542. self.delete_selection_shape()
  3543. def on_workspace_modified(self):
  3544. # self.save_defaults(silent=True)
  3545. self.plotcanvas.delete_workspace()
  3546. self.preferencesUiManager.defaults_read_form()
  3547. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3548. def on_workspace(self):
  3549. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3550. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3551. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3552. else:
  3553. self.plotcanvas.delete_workspace()
  3554. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3555. self.preferencesUiManager.defaults_read_form()
  3556. # self.save_defaults(silent=True)
  3557. def on_workspace_toggle(self):
  3558. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3559. try:
  3560. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3561. except TypeError:
  3562. pass
  3563. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3564. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3565. self.on_workspace()
  3566. def on_cursor_type(self, val):
  3567. """
  3568. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3569. :return: None
  3570. """
  3571. self.app_cursor.enabled = False
  3572. if val == 'small':
  3573. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3574. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3575. self.app_cursor = self.plotcanvas.new_cursor()
  3576. else:
  3577. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3578. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3579. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3580. if self.ui.grid_snap_btn.isChecked():
  3581. self.app_cursor.enabled = True
  3582. else:
  3583. self.app_cursor.enabled = False
  3584. def on_tool_add_keypress(self):
  3585. # ## Current application units in Upper Case
  3586. self.units = self.defaults['units'].upper()
  3587. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3588. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3589. if notebook_widget_name == 'properties_tab':
  3590. if self.collection.get_active().kind == 'geometry':
  3591. # Tool add works for Geometry only if Advanced is True in Preferences
  3592. if self.defaults["global_app_level"] == 'a':
  3593. tool_add_popup = FCInputDialog(title="New Tool ...",
  3594. text='Enter a Tool Diameter:',
  3595. min=0.0000, max=99.9999, decimals=4)
  3596. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3597. val, ok = tool_add_popup.get_value()
  3598. if ok:
  3599. if float(val) == 0:
  3600. self.inform.emit('[WARNING_NOTCL] %s' %
  3601. _("Please enter a tool diameter with non-zero value, in Float format."))
  3602. return
  3603. self.collection.get_active().on_tool_add(dia=float(val))
  3604. else:
  3605. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3606. else:
  3607. msgbox = QtWidgets.QMessageBox()
  3608. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3609. "Go to Preferences -> General - Show Advanced Options."))
  3610. msgbox.setWindowTitle("Tool adding ...")
  3611. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3612. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3613. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3614. msgbox.setDefaultButton(bt_ok)
  3615. msgbox.exec_()
  3616. # work only if the notebook tab on focus is the Tools_Tab
  3617. if notebook_widget_name == 'tool_tab':
  3618. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3619. # and only if the tool is NCC Tool
  3620. if tool_widget == self.ncclear_tool.toolName:
  3621. self.ncclear_tool.on_add_tool_by_key()
  3622. # and only if the tool is Paint Area Tool
  3623. elif tool_widget == self.paint_tool.toolName:
  3624. self.paint_tool.on_add_tool_by_key()
  3625. # and only if the tool is Solder Paste Dispensing Tool
  3626. elif tool_widget == self.paste_tool.toolName:
  3627. self.paste_tool.on_add_tool_by_key()
  3628. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3629. # See description below.
  3630. def on_delete_keypress(self):
  3631. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3632. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3633. if notebook_widget_name == 'properties_tab':
  3634. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3635. self.collection.get_active().on_tool_delete()
  3636. # work only if the notebook tab on focus is the Tools_Tab
  3637. elif notebook_widget_name == 'tool_tab':
  3638. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3639. # and only if the tool is NCC Tool
  3640. if tool_widget == self.ncclear_tool.toolName:
  3641. self.ncclear_tool.on_tool_delete()
  3642. # and only if the tool is Paint Tool
  3643. elif tool_widget == self.paint_tool.toolName:
  3644. self.paint_tool.on_tool_delete()
  3645. # and only if the tool is Solder Paste Dispensing Tool
  3646. elif tool_widget == self.paste_tool.toolName:
  3647. self.paste_tool.on_tool_delete()
  3648. # and only if the tool is Isolation Tool
  3649. elif tool_widget == self.isolation_tool.toolName:
  3650. self.isolation_tool.on_tool_delete()
  3651. else:
  3652. self.on_delete()
  3653. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3654. # some screens you have to be careful where you hover with your mouse.
  3655. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3656. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3657. # Complicated, I know :)
  3658. def on_delete(self, force_deletion=False):
  3659. """
  3660. Delete the currently selected FlatCAMObjs.
  3661. :param force_deletion: used by Tcl command
  3662. :return: None
  3663. """
  3664. self.defaults.report_usage("on_delete()")
  3665. response = None
  3666. bt_ok = None
  3667. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3668. # a geometry object before we update it.
  3669. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3670. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3671. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3672. msgbox = QtWidgets.QMessageBox()
  3673. msgbox.setWindowTitle(_("Delete objects"))
  3674. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3675. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3676. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3677. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3678. "the selected objects?"))
  3679. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3680. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3681. msgbox.setDefaultButton(bt_ok)
  3682. msgbox.exec_()
  3683. response = msgbox.clickedButton()
  3684. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3685. response = bt_ok
  3686. if response == bt_ok:
  3687. if self.collection.get_active():
  3688. self.log.debug("App.on_delete()")
  3689. for obj_active in self.collection.get_selected():
  3690. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3691. if obj_active.kind == 'gerber':
  3692. obj_active.mark_shapes_storage.clear()
  3693. obj_active.mark_shapes.clear(update=True)
  3694. obj_active.mark_shapes.enabled = False
  3695. elif obj_active.kind == 'cncjob':
  3696. try:
  3697. obj_active.text_col.enabled = False
  3698. del obj_active.text_col
  3699. obj_active.annotation.clear(update=True)
  3700. del obj_active.annotation
  3701. obj_active.probing_shapes.clear(update=True)
  3702. except AttributeError as e:
  3703. log.debug(
  3704. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3705. )
  3706. while self.collection.get_selected():
  3707. self.delete_first_selected()
  3708. # make sure that the selection shape is deleted, too
  3709. self.delete_selection_shape()
  3710. # if there are no longer objects delete also the exclusion areas shapes
  3711. if not self.collection.get_list():
  3712. self.exc_areas.clear_shapes()
  3713. self.inform.emit('%s...' % _("Object(s) deleted"))
  3714. else:
  3715. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3716. else:
  3717. self.inform.emit(_("Save the work in Editor and try again ..."))
  3718. def delete_first_selected(self):
  3719. # Keep this for later
  3720. try:
  3721. sel_obj = self.collection.get_active()
  3722. name = sel_obj.options["name"]
  3723. isPlotted = sel_obj.options["plot"]
  3724. except AttributeError:
  3725. self.log.debug("Nothing selected for deletion")
  3726. return
  3727. if self.is_legacy is True:
  3728. # Remove plot only if the object was plotted otherwise delaxes will fail
  3729. if isPlotted:
  3730. try:
  3731. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3732. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3733. except Exception as e:
  3734. log.debug("App.delete_first_selected() --> %s" % str(e))
  3735. self.plotcanvas.auto_adjust_axes()
  3736. # Remove from dictionary
  3737. self.collection.delete_active()
  3738. # Clear form
  3739. self.setup_default_properties_tab()
  3740. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3741. def on_set_origin(self):
  3742. """
  3743. Set the origin to the left mouse click position
  3744. :return: None
  3745. """
  3746. # display the message for the user
  3747. # and ask him to click on the desired position
  3748. self.defaults.report_usage("on_set_origin()")
  3749. def origin_replot():
  3750. def worker_task():
  3751. with self.proc_container.new('%s...' % _("Plotting")):
  3752. for obj in self.collection.get_list():
  3753. obj.plot()
  3754. self.plotcanvas.fit_view()
  3755. if self.is_legacy:
  3756. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3757. else:
  3758. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3759. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3760. self.inform.emit(_('Click to set the origin ...'))
  3761. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3762. # first disconnect it as it may have been used by something else
  3763. try:
  3764. self.replot_signal.disconnect()
  3765. except TypeError:
  3766. pass
  3767. self.replot_signal[list].connect(origin_replot)
  3768. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3769. """
  3770. :param event:
  3771. :param location:
  3772. :param noplot:
  3773. :param use_thread:
  3774. :return:
  3775. """
  3776. noplot_sig = noplot
  3777. def worker_task():
  3778. with self.proc_container.new(_("Setting Origin...")):
  3779. obj_list = self.collection.get_list()
  3780. for obj in obj_list:
  3781. obj.offset((x, y))
  3782. self.app_obj.object_changed.emit(obj)
  3783. # Update the object bounding box options
  3784. a, b, c, d = obj.bounds()
  3785. obj.options['xmin'] = a
  3786. obj.options['ymin'] = b
  3787. obj.options['xmax'] = c
  3788. obj.options['ymax'] = d
  3789. self.inform.emit('[success] %s...' % _('Origin set'))
  3790. for obj in obj_list:
  3791. out_name = obj.options["name"]
  3792. if obj.kind == 'gerber':
  3793. obj.source_file = self.f_handlers.export_gerber(
  3794. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3795. elif obj.kind == 'excellon':
  3796. obj.source_file = self.f_handlers.export_excellon(
  3797. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3798. if noplot_sig is False:
  3799. self.replot_signal.emit([])
  3800. if location is not None:
  3801. if len(location) != 2:
  3802. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3803. return 'fail'
  3804. x, y = location
  3805. if use_thread is True:
  3806. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3807. else:
  3808. worker_task()
  3809. self.should_we_save = True
  3810. return
  3811. if event is not None and event.button == 1:
  3812. if self.is_legacy is False:
  3813. event_pos = event.pos
  3814. else:
  3815. event_pos = (event.xdata, event.ydata)
  3816. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3817. if self.grid_status():
  3818. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3819. else:
  3820. pos = pos_canvas
  3821. x = 0 - pos[0]
  3822. y = 0 - pos[1]
  3823. if use_thread is True:
  3824. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3825. else:
  3826. worker_task()
  3827. self.should_we_save = True
  3828. def on_move2origin(self, use_thread=True):
  3829. """
  3830. Move selected objects to origin.
  3831. :param use_thread: Control if to use threaded operation. Boolean.
  3832. :return:
  3833. """
  3834. def worker_task():
  3835. with self.proc_container.new(_("Moving to Origin...")):
  3836. obj_list = self.collection.get_selected()
  3837. if not obj_list:
  3838. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3839. return
  3840. xminlist = []
  3841. yminlist = []
  3842. # first get a bounding box to fit all
  3843. for obj in obj_list:
  3844. xmin, ymin, xmax, ymax = obj.bounds()
  3845. xminlist.append(xmin)
  3846. yminlist.append(ymin)
  3847. # get the minimum x,y for all objects selected
  3848. x = min(xminlist)
  3849. y = min(yminlist)
  3850. for obj in obj_list:
  3851. obj.offset((-x, -y))
  3852. self.app_obj.object_changed.emit(obj)
  3853. # Update the object bounding box options
  3854. a, b, c, d = obj.bounds()
  3855. obj.options['xmin'] = a
  3856. obj.options['ymin'] = b
  3857. obj.options['xmax'] = c
  3858. obj.options['ymax'] = d
  3859. for obj in obj_list:
  3860. obj.plot()
  3861. for obj in obj_list:
  3862. out_name = obj.options["name"]
  3863. if obj.kind == 'gerber':
  3864. obj.source_file = self.f_handlers.export_gerber(
  3865. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3866. elif obj.kind == 'excellon':
  3867. obj.source_file = self.f_handlers.export_excellon(
  3868. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3869. self.inform.emit('[success] %s...' % _('Origin set'))
  3870. if use_thread is True:
  3871. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3872. else:
  3873. worker_task()
  3874. self.should_we_save = True
  3875. def on_jump_to(self, custom_location=None, fit_center=True):
  3876. """
  3877. Jump to a location by setting the mouse cursor location.
  3878. :param custom_location: Jump to a specified point. (x, y) tuple.
  3879. :param fit_center: If to fit view. Boolean.
  3880. :return:
  3881. """
  3882. self.defaults.report_usage("on_jump_to()")
  3883. if not custom_location:
  3884. dia_box_location = None
  3885. try:
  3886. dia_box_location = eval(self.clipboard.text())
  3887. except Exception:
  3888. pass
  3889. if type(dia_box_location) == tuple:
  3890. dia_box_location = str(dia_box_location)
  3891. else:
  3892. dia_box_location = None
  3893. # dia_box = Dialog_box(title=_("Jump to ..."),
  3894. # label=_("Enter the coordinates in format X,Y:"),
  3895. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3896. # initial_text=dia_box_location)
  3897. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3898. label=_("Enter the coordinates in format X,Y:"),
  3899. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3900. initial_text=dia_box_location,
  3901. reference=self.defaults['global_jump_ref'])
  3902. if dia_box.ok is True:
  3903. try:
  3904. location = eval(dia_box.location)
  3905. if not isinstance(location, tuple):
  3906. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3907. return
  3908. if dia_box.reference == 'rel':
  3909. rel_x = self.mouse[0] + location[0]
  3910. rel_y = self.mouse[1] + location[1]
  3911. location = (rel_x, rel_y)
  3912. self.defaults['global_jump_ref'] = dia_box.reference
  3913. except Exception:
  3914. return
  3915. else:
  3916. return
  3917. else:
  3918. location = custom_location
  3919. self.jump_signal.emit(location)
  3920. if fit_center:
  3921. self.plotcanvas.fit_center(loc=location)
  3922. cursor = QtGui.QCursor()
  3923. if self.is_legacy is False:
  3924. # I don't know where those differences come from but they are constant for the current
  3925. # execution of the application and they are multiples of a value around 0.0263mm.
  3926. # In a random way sometimes they are more sometimes they are less
  3927. # if units == 'MM':
  3928. # cal_factor = 0.0263
  3929. # else:
  3930. # cal_factor = 0.0263 / 25.4
  3931. cal_location = (location[0], location[1])
  3932. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3933. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3934. j_pos = (
  3935. int(canvas_origin.x() + round(jump_loc[0])),
  3936. int(canvas_origin.y() + round(jump_loc[1]))
  3937. )
  3938. cursor.setPos(j_pos[0], j_pos[1])
  3939. else:
  3940. # find the canvas origin which is in the top left corner
  3941. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3942. # determine the coordinates for the lowest left point of the canvas
  3943. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3944. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3945. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3946. # canvas) and the point (width, height) is in the top-right location
  3947. loc = self.plotcanvas.axes.transData.transform_point(location)
  3948. j_pos = (
  3949. int(x0 + loc[0]),
  3950. int(y0 - loc[1])
  3951. )
  3952. cursor.setPos(j_pos[0], j_pos[1])
  3953. self.plotcanvas.mouse = [location[0], location[1]]
  3954. if self.defaults["global_cursor_color_enabled"] is True:
  3955. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3956. else:
  3957. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3958. if self.grid_status():
  3959. # Update cursor
  3960. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3961. symbol='++', edge_color=self.cursor_color_3D,
  3962. edge_width=self.defaults["global_cursor_width"],
  3963. size=self.defaults["global_cursor_size"])
  3964. # Set the relative position label
  3965. dx = location[0] - float(self.rel_point1[0])
  3966. dy = location[1] - float(self.rel_point1[1])
  3967. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3968. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3969. # Set the position label
  3970. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3971. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3972. units = self.defaults["units"].lower()
  3973. self.plotcanvas.text_hud.text = \
  3974. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3975. dx, units, dy, units, location[0], units, location[1], units)
  3976. self.inform.emit('[success] %s' % _("Done."))
  3977. return location
  3978. def on_locate(self, obj, fit_center=True):
  3979. """
  3980. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3981. :param obj: The object on which to locate certain points
  3982. :param fit_center: If to fit view. Boolean.
  3983. :return: A point location. (x, y) tuple.
  3984. """
  3985. self.defaults.report_usage("on_locate()")
  3986. if obj is None:
  3987. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3988. return 'fail'
  3989. class DialogBoxChoice(QtWidgets.QDialog):
  3990. def __init__(self, title=None, icon=None, choice='bl'):
  3991. """
  3992. :param title: string with the window title
  3993. """
  3994. super(DialogBoxChoice, self).__init__()
  3995. self.ok = False
  3996. self.setWindowIcon(icon)
  3997. self.setWindowTitle(str(title))
  3998. self.form = QtWidgets.QFormLayout(self)
  3999. self.ref_radio = RadioSet([
  4000. {"label": _("Bottom-Left"), "value": "bl"},
  4001. {"label": _("Top-Left"), "value": "tl"},
  4002. {"label": _("Bottom-Right"), "value": "br"},
  4003. {"label": _("Top-Right"), "value": "tr"},
  4004. {"label": _("Center"), "value": "c"}
  4005. ], orientation='vertical', stretch=False)
  4006. self.ref_radio.set_value(choice)
  4007. self.form.addRow(self.ref_radio)
  4008. self.button_box = QtWidgets.QDialogButtonBox(
  4009. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4010. Qt.Horizontal, parent=self)
  4011. self.form.addRow(self.button_box)
  4012. self.button_box.accepted.connect(self.accept)
  4013. self.button_box.rejected.connect(self.reject)
  4014. if self.exec_() == QtWidgets.QDialog.Accepted:
  4015. self.ok = True
  4016. self.location_point = self.ref_radio.get_value()
  4017. else:
  4018. self.ok = False
  4019. self.location_point = None
  4020. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4021. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4022. choice=self.defaults['global_locate_pt'])
  4023. if dia_box.ok is True:
  4024. try:
  4025. location_point = dia_box.location_point
  4026. self.defaults['global_locate_pt'] = dia_box.location_point
  4027. except Exception:
  4028. return
  4029. else:
  4030. return
  4031. loc_b = obj.bounds()
  4032. if location_point == 'bl':
  4033. location = (loc_b[0], loc_b[1])
  4034. elif location_point == 'tl':
  4035. location = (loc_b[0], loc_b[3])
  4036. elif location_point == 'br':
  4037. location = (loc_b[2], loc_b[1])
  4038. elif location_point == 'tr':
  4039. location = (loc_b[2], loc_b[3])
  4040. else:
  4041. # center
  4042. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4043. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4044. location = (cx, cy)
  4045. self.locate_signal.emit(location, location_point)
  4046. if fit_center:
  4047. self.plotcanvas.fit_center(loc=location)
  4048. cursor = QtGui.QCursor()
  4049. if self.is_legacy is False:
  4050. # I don't know where those differences come from but they are constant for the current
  4051. # execution of the application and they are multiples of a value around 0.0263mm.
  4052. # In a random way sometimes they are more sometimes they are less
  4053. # if units == 'MM':
  4054. # cal_factor = 0.0263
  4055. # else:
  4056. # cal_factor = 0.0263 / 25.4
  4057. cal_location = (location[0], location[1])
  4058. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4059. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4060. j_pos = (
  4061. int(canvas_origin.x() + round(jump_loc[0])),
  4062. int(canvas_origin.y() + round(jump_loc[1]))
  4063. )
  4064. cursor.setPos(j_pos[0], j_pos[1])
  4065. else:
  4066. # find the canvas origin which is in the top left corner
  4067. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4068. # determine the coordinates for the lowest left point of the canvas
  4069. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4070. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4071. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4072. # canvas) and the point (width, height) is in the top-right location
  4073. loc = self.plotcanvas.axes.transData.transform_point(location)
  4074. j_pos = (
  4075. int(x0 + loc[0]),
  4076. int(y0 - loc[1])
  4077. )
  4078. cursor.setPos(j_pos[0], j_pos[1])
  4079. self.plotcanvas.mouse = [location[0], location[1]]
  4080. if self.defaults["global_cursor_color_enabled"] is True:
  4081. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4082. else:
  4083. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4084. if self.grid_status():
  4085. # Update cursor
  4086. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4087. symbol='++', edge_color=self.cursor_color_3D,
  4088. edge_width=self.defaults["global_cursor_width"],
  4089. size=self.defaults["global_cursor_size"])
  4090. # Set the relative position label
  4091. self.dx = location[0] - float(self.rel_point1[0])
  4092. self.dy = location[1] - float(self.rel_point1[1])
  4093. # Set the position label
  4094. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4095. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4096. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4097. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4098. units = self.defaults["units"].lower()
  4099. self.plotcanvas.text_hud.text = \
  4100. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4101. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4102. self.inform.emit('[success] %s' % _("Done."))
  4103. return location
  4104. def on_copy_command(self):
  4105. """
  4106. Will copy a selection of objects, creating new objects.
  4107. :return:
  4108. """
  4109. self.defaults.report_usage("on_copy_command()")
  4110. def initialize(obj_init, app):
  4111. """
  4112. :param obj_init: the new object
  4113. :type obj_init: class
  4114. :param app: An instance of the App class
  4115. :type app: App
  4116. :return: None
  4117. :rtype:
  4118. """
  4119. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4120. try:
  4121. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4122. except AttributeError:
  4123. pass
  4124. try:
  4125. obj_init.apertures = deepcopy(obj.apertures)
  4126. except AttributeError:
  4127. pass
  4128. try:
  4129. if obj.tools:
  4130. obj_init.tools = deepcopy(obj.tools)
  4131. except Exception as err:
  4132. log.debug("App.on_copy_command() --> %s" % str(err))
  4133. try:
  4134. obj_init.source_file = deepcopy(obj.source_file)
  4135. except (AttributeError, TypeError):
  4136. pass
  4137. def initialize_excellon(obj_init, app):
  4138. obj_init.source_file = deepcopy(obj.source_file)
  4139. obj_init.tools = deepcopy(obj.tools)
  4140. # drills are offset, so they need to be deep copied
  4141. obj_init.drills = deepcopy(obj.drills)
  4142. # slots are offset, so they need to be deep copied
  4143. obj_init.slots = deepcopy(obj.slots)
  4144. obj_init.create_geometry()
  4145. def initialize_script(obj_init, app_obj):
  4146. obj_init.source_file = deepcopy(obj.source_file)
  4147. def initialize_document(obj_init, app_obj):
  4148. obj_init.source_file = deepcopy(obj.source_file)
  4149. for obj in self.collection.get_selected():
  4150. obj_name = obj.options["name"]
  4151. try:
  4152. if isinstance(obj, ExcellonObject):
  4153. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4154. elif isinstance(obj, GerberObject):
  4155. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4156. elif isinstance(obj, GeometryObject):
  4157. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4158. elif isinstance(obj, ScriptObject):
  4159. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4160. elif isinstance(obj, DocumentObject):
  4161. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4162. except Exception as e:
  4163. return "Operation failed: %s" % str(e)
  4164. def on_copy_object2(self, custom_name):
  4165. def initialize_geometry(obj_init, app):
  4166. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4167. try:
  4168. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4169. except AttributeError:
  4170. pass
  4171. try:
  4172. obj_init.apertures = deepcopy(obj.apertures)
  4173. except AttributeError:
  4174. pass
  4175. try:
  4176. if obj.tools:
  4177. obj_init.tools = deepcopy(obj.tools)
  4178. except Exception as ee:
  4179. log.debug("on_copy_object2() --> %s" % str(ee))
  4180. def initialize_gerber(obj_init, app):
  4181. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4182. obj_init.apertures = deepcopy(obj.apertures)
  4183. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4184. def initialize_excellon(obj_init, app):
  4185. obj_init.tools = deepcopy(obj.tools)
  4186. # drills are offset, so they need to be deep copied
  4187. obj_init.drills = deepcopy(obj.drills)
  4188. # slots are offset, so they need to be deep copied
  4189. obj_init.slots = deepcopy(obj.slots)
  4190. obj_init.create_geometry()
  4191. for obj in self.collection.get_selected():
  4192. obj_name = obj.options["name"]
  4193. try:
  4194. if isinstance(obj, ExcellonObject):
  4195. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4196. elif isinstance(obj, GerberObject):
  4197. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4198. elif isinstance(obj, GeometryObject):
  4199. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4200. except Exception as er:
  4201. return "Operation failed: %s" % str(er)
  4202. def on_rename_object(self, text):
  4203. """
  4204. Will rename an object.
  4205. :param text: New name for the object.
  4206. :return:
  4207. """
  4208. self.defaults.report_usage("on_rename_object()")
  4209. named_obj = self.collection.get_active()
  4210. for obj in named_obj:
  4211. if obj is list:
  4212. self.on_rename_object(text)
  4213. else:
  4214. try:
  4215. obj.options['name'] = text
  4216. except Exception as e:
  4217. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4218. def convert_any2geo(self):
  4219. """
  4220. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4221. :return:
  4222. """
  4223. self.defaults.report_usage("convert_any2geo()")
  4224. def initialize(obj_init, app):
  4225. obj_init.solid_geometry = obj.solid_geometry
  4226. try:
  4227. obj_init.follow_geometry = obj.follow_geometry
  4228. except AttributeError:
  4229. pass
  4230. try:
  4231. obj_init.apertures = obj.apertures
  4232. except AttributeError:
  4233. pass
  4234. try:
  4235. if obj.tools:
  4236. obj_init.tools = obj.tools
  4237. except AttributeError:
  4238. pass
  4239. def initialize_excellon(obj_init, app):
  4240. # objs = self.collection.get_selected()
  4241. # GeometryObject.merge(objs, obj)
  4242. solid_geo = []
  4243. for tool in obj.tools:
  4244. for geo in obj.tools[tool]['solid_geometry']:
  4245. solid_geo.append(geo)
  4246. obj_init.solid_geometry = deepcopy(solid_geo)
  4247. if not self.collection.get_selected():
  4248. log.warning("App.convert_any2geo --> No object selected")
  4249. self.inform.emit('[WARNING_NOTCL] %s' %
  4250. _("No object is selected. Select an object and try again."))
  4251. return
  4252. for obj in self.collection.get_selected():
  4253. obj_name = obj.options["name"]
  4254. try:
  4255. if obj.kind == 'excellon':
  4256. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4257. else:
  4258. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4259. except Exception as e:
  4260. return "Operation failed: %s" % str(e)
  4261. def convert_any2gerber(self):
  4262. """
  4263. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4264. :return:
  4265. """
  4266. def initialize_geometry(obj_init, app):
  4267. apertures = {}
  4268. apid = 0
  4269. apertures[str(apid)] = {}
  4270. apertures[str(apid)]['geometry'] = []
  4271. for obj_orig in obj.solid_geometry:
  4272. new_elem = {}
  4273. new_elem['solid'] = obj_orig
  4274. try:
  4275. new_elem['follow'] = obj_orig.exterior
  4276. except AttributeError:
  4277. pass
  4278. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4279. apertures[str(apid)]['size'] = 0.0
  4280. apertures[str(apid)]['type'] = 'C'
  4281. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4282. obj_init.apertures = deepcopy(apertures)
  4283. def initialize_excellon(obj_init, app):
  4284. apertures = {}
  4285. apid = 10
  4286. for tool in obj.tools:
  4287. apertures[str(apid)] = {}
  4288. apertures[str(apid)]['geometry'] = []
  4289. for geo in obj.tools[tool]['solid_geometry']:
  4290. new_el = {}
  4291. new_el['solid'] = geo
  4292. new_el['follow'] = geo.exterior
  4293. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4294. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4295. apertures[str(apid)]['type'] = 'C'
  4296. apid += 1
  4297. # create solid_geometry
  4298. solid_geometry = []
  4299. for apid in apertures:
  4300. for geo_el in apertures[apid]['geometry']:
  4301. solid_geometry.append(geo_el['solid'])
  4302. solid_geometry = MultiPolygon(solid_geometry)
  4303. solid_geometry = solid_geometry.buffer(0.0000001)
  4304. obj_init.solid_geometry = deepcopy(solid_geometry)
  4305. obj_init.apertures = deepcopy(apertures)
  4306. # clear the working objects (perhaps not necessary due of Python GC)
  4307. apertures.clear()
  4308. if not self.collection.get_selected():
  4309. log.warning("App.convert_any2gerber --> No object selected")
  4310. self.inform.emit('[WARNING_NOTCL] %s' %
  4311. _("No object is selected. Select an object and try again."))
  4312. return
  4313. for obj in self.collection.get_selected():
  4314. obj_name = obj.options["name"]
  4315. try:
  4316. if obj.kind == 'excellon':
  4317. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4318. elif obj.kind == 'geometry':
  4319. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4320. else:
  4321. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4322. except Exception as e:
  4323. return "Operation failed: %s" % str(e)
  4324. def convert_any2excellon(self):
  4325. """
  4326. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4327. :return:
  4328. """
  4329. def initialize_geometry(obj_init, app):
  4330. tools = {}
  4331. tooluid = 1
  4332. obj_init.solid_geometry = []
  4333. for geo in obj.solid_geometry:
  4334. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4335. continue
  4336. minx, miny, maxx, maxy = geo.bounds
  4337. new_dia = min([maxx-minx, maxy-miny])
  4338. new_drill = geo.centroid
  4339. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4340. current_tooldias = []
  4341. if tools:
  4342. for tool in tools:
  4343. if tools[tool] and 'tooldia' in tools[tool]:
  4344. current_tooldias.append(tools[tool]['tooldia'])
  4345. if new_dia in current_tooldias:
  4346. for tool in tools:
  4347. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4348. new_dia)):
  4349. tools[tool]['drills'].append(new_drill)
  4350. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4351. else:
  4352. tools[tooluid] = {}
  4353. tools[tooluid]['tooldia'] = new_dia
  4354. tools[tooluid]['drills'] = [new_drill]
  4355. tools[tooluid]['slots'] = []
  4356. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4357. tooluid += 1
  4358. try:
  4359. obj_init.solid_geometry.append(new_drill_geo)
  4360. except (TypeError, AttributeError):
  4361. obj_init.solid_geometry = [new_drill_geo]
  4362. obj_init.tools = deepcopy(tools)
  4363. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4364. def initialize_gerber(obj_init, app):
  4365. tools = {}
  4366. tooluid = 1
  4367. obj_init.solid_geometry = []
  4368. for apid in obj.apertures:
  4369. if 'geometry' in obj.apertures[apid]:
  4370. for geo_dict in obj.apertures[apid]['geometry']:
  4371. if 'follow' in geo_dict:
  4372. if isinstance(geo_dict['follow'], Point):
  4373. geo = geo_dict['solid']
  4374. minx, miny, maxx, maxy = geo.bounds
  4375. new_dia = min([maxx - minx, maxy - miny])
  4376. new_drill = geo.centroid
  4377. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4378. current_tooldias = []
  4379. if tools:
  4380. for tool in tools:
  4381. if tools[tool] and 'tooldia' in tools[tool]:
  4382. current_tooldias.append(
  4383. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4384. )
  4385. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4386. for tool in tools:
  4387. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4388. '%.*f' % (self.decimals, new_dia)):
  4389. if new_drill not in tools[tool]['drills']:
  4390. tools[tool]['drills'].append(new_drill)
  4391. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4392. else:
  4393. tools[tooluid] = {}
  4394. tools[tooluid]['tooldia'] = new_dia
  4395. tools[tooluid]['drills'] = [new_drill]
  4396. tools[tooluid]['slots'] = []
  4397. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4398. tooluid += 1
  4399. try:
  4400. obj_init.solid_geometry.append(new_drill_geo)
  4401. except (TypeError, AttributeError):
  4402. obj_init.solid_geometry = [new_drill_geo]
  4403. elif isinstance(geo_dict['follow'], LineString):
  4404. geo_coords = list(geo_dict['follow'].coords)
  4405. # slots can have only a start and stop point and no intermediate points
  4406. if len(geo_coords) != 2:
  4407. continue
  4408. geo = geo_dict['solid']
  4409. try:
  4410. new_dia = obj.apertures[apid]['size']
  4411. except Exception:
  4412. continue
  4413. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4414. new_slot_geo = geo
  4415. current_tooldias = []
  4416. if tools:
  4417. for tool in tools:
  4418. if tools[tool] and 'tooldia' in tools[tool]:
  4419. current_tooldias.append(
  4420. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4421. )
  4422. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4423. for tool in tools:
  4424. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4425. '%.*f' % (self.decimals, new_dia)):
  4426. if new_slot not in tools[tool]['slots']:
  4427. tools[tool]['slots'].append(new_slot)
  4428. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4429. else:
  4430. tools[tooluid] = {}
  4431. tools[tooluid]['tooldia'] = new_dia
  4432. tools[tooluid]['drills'] = []
  4433. tools[tooluid]['slots'] = [new_slot]
  4434. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4435. tooluid += 1
  4436. try:
  4437. obj_init.solid_geometry.append(new_slot_geo)
  4438. except (TypeError, AttributeError):
  4439. obj_init.solid_geometry = [new_slot_geo]
  4440. obj_init.tools = deepcopy(tools)
  4441. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4442. if not self.collection.get_selected():
  4443. log.warning("App.convert_any2excellon--> No object selected")
  4444. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4445. return
  4446. for obj in self.collection.get_selected():
  4447. obj_name = obj.options["name"]
  4448. try:
  4449. if obj.kind == 'gerber':
  4450. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4451. elif obj.kind == 'geometry':
  4452. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4453. else:
  4454. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4455. except Exception as e:
  4456. return "Operation failed: %s" % str(e)
  4457. def abort_all_tasks(self):
  4458. """
  4459. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4460. on the first possible occasion.
  4461. :return:
  4462. """
  4463. if self.abort_flag is False:
  4464. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4465. self.abort_flag = True
  4466. self.cleanup.emit()
  4467. def app_is_idle(self):
  4468. if self.abort_flag:
  4469. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4470. self.abort_flag = False
  4471. def on_selectall(self):
  4472. """
  4473. Will draw a selection box shape around the selected objects.
  4474. :return:
  4475. """
  4476. self.defaults.report_usage("on_selectall()")
  4477. # delete the possible selection box around a possible selected object
  4478. self.delete_selection_shape()
  4479. for name in self.collection.get_names():
  4480. self.collection.set_active(name)
  4481. curr_sel_obj = self.collection.get_by_name(name)
  4482. # create the selection box around the selected object
  4483. if self.defaults['global_selection_shape'] is True:
  4484. self.draw_selection_shape(curr_sel_obj)
  4485. def on_toggle_preferences(self):
  4486. pref_open = False
  4487. for idx in range(self.ui.plot_tab_area.count()):
  4488. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4489. pref_open = True
  4490. if pref_open:
  4491. for idx in range(self.ui.plot_tab_area.count()):
  4492. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4493. self.ui.plot_tab_area.removeTab(idx)
  4494. break
  4495. self.ui.pref_status_label.setStyleSheet("")
  4496. else:
  4497. self.on_preferences()
  4498. def on_preferences(self):
  4499. """
  4500. Adds the Preferences in a Tab in Plot Area
  4501. :return:
  4502. """
  4503. # add the tab if it was closed
  4504. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4505. # delete the absolute and relative position and messages in the infobar
  4506. # self.ui.position_label.setText("")
  4507. # self.ui.rel_position_label.setText("")
  4508. # hide coordinates toolbars in the infobar while in DB
  4509. self.ui.coords_toolbar.hide()
  4510. self.ui.delta_coords_toolbar.hide()
  4511. # Switch plot_area to preferences page
  4512. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4513. # self.ui.show()
  4514. self.ui.pref_status_label.setStyleSheet("""
  4515. QLabel
  4516. {
  4517. color: black;
  4518. background-color: lightseagreen;
  4519. }
  4520. """
  4521. )
  4522. # detect changes in the preferences
  4523. for idx in range(self.ui.pref_tab_area.count()):
  4524. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4525. try:
  4526. try:
  4527. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4528. except (TypeError, AttributeError):
  4529. pass
  4530. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4531. except AttributeError:
  4532. pass
  4533. try:
  4534. try:
  4535. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4536. except (TypeError, AttributeError):
  4537. pass
  4538. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4539. except AttributeError:
  4540. pass
  4541. try:
  4542. try:
  4543. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4544. except (TypeError, AttributeError):
  4545. pass
  4546. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4547. except AttributeError:
  4548. pass
  4549. try:
  4550. try:
  4551. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4552. except (TypeError, AttributeError):
  4553. pass
  4554. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4555. except AttributeError:
  4556. pass
  4557. try:
  4558. try:
  4559. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4560. except (TypeError, AttributeError):
  4561. pass
  4562. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4563. except AttributeError:
  4564. pass
  4565. def on_tools_database(self, source='app'):
  4566. """
  4567. Adds the Tools Database in a Tab in Plot Area.
  4568. :return:
  4569. """
  4570. for idx in range(self.ui.plot_tab_area.count()):
  4571. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4572. # there can be only one instance of Tools Database at one time
  4573. return
  4574. if source == 'app':
  4575. self.tools_db_tab = ToolsDB2(
  4576. app=self,
  4577. parent=self.ui,
  4578. callback_on_edited=self.on_tools_db_edited,
  4579. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4580. )
  4581. elif source == 'ncc':
  4582. self.tools_db_tab = ToolsDB2(
  4583. app=self,
  4584. parent=self.ui,
  4585. callback_on_edited=self.on_tools_db_edited,
  4586. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4587. )
  4588. elif source == 'paint':
  4589. self.tools_db_tab = ToolsDB2(
  4590. app=self,
  4591. parent=self.ui,
  4592. callback_on_edited=self.on_tools_db_edited,
  4593. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4594. )
  4595. elif source == 'iso':
  4596. self.tools_db_tab = ToolsDB2(
  4597. app=self,
  4598. parent=self.ui,
  4599. callback_on_edited=self.on_tools_db_edited,
  4600. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4601. )
  4602. elif source == 'cutout':
  4603. self.tools_db_tab = ToolsDB2(
  4604. app=self,
  4605. parent=self.ui,
  4606. callback_on_edited=self.on_tools_db_edited,
  4607. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4608. )
  4609. # add the tab if it was closed
  4610. try:
  4611. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4612. self.tools_db_tab.setObjectName("database_tab")
  4613. except Exception as e:
  4614. log.debug("App.on_tools_database() --> %s" % str(e))
  4615. return
  4616. # delete the absolute and relative position and messages in the infobar
  4617. # self.ui.position_label.setText("")
  4618. # self.ui.rel_position_label.setText("")
  4619. # hide coordinates toolbars in the infobar while in DB
  4620. self.ui.coords_toolbar.hide()
  4621. self.ui.delta_coords_toolbar.hide()
  4622. # Switch plot_area to preferences page
  4623. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4624. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4625. self.tools_db_tab.ui_connect()
  4626. def on_tools_db_edited(self):
  4627. """
  4628. Executed whenever a tool is edited in Tools Database.
  4629. Will color the text of the Tools Database tab to Red color.
  4630. :return:
  4631. """
  4632. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4633. for idx in range(self.ui.plot_tab_area.count()):
  4634. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4635. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4636. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4637. self.tools_db_changed_flag = True
  4638. def on_geometry_tool_add_from_db_executed(self, tool):
  4639. """
  4640. Here add the tool from DB in the selected geometry object.
  4641. :return:
  4642. """
  4643. tool_from_db = deepcopy(tool)
  4644. obj = self.collection.get_active()
  4645. if obj.kind == 'geometry':
  4646. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4647. # close the tab and delete it
  4648. for idx in range(self.ui.plot_tab_area.count()):
  4649. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4650. wdg = self.ui.plot_tab_area.widget(idx)
  4651. wdg.deleteLater()
  4652. self.ui.plot_tab_area.removeTab(idx)
  4653. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4654. elif obj.kind == 'gerber':
  4655. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4656. # close the tab and delete it
  4657. for idx in range(self.ui.plot_tab_area.count()):
  4658. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4659. wdg = self.ui.plot_tab_area.widget(idx)
  4660. wdg.deleteLater()
  4661. self.ui.plot_tab_area.removeTab(idx)
  4662. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4663. else:
  4664. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4665. def on_plot_area_tab_closed(self, tab_obj_name):
  4666. """
  4667. Executed whenever a QTab is closed in the Plot Area.
  4668. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4669. :return:
  4670. """
  4671. if tab_obj_name == "preferences_tab":
  4672. self.preferencesUiManager.on_close_preferences_tab()
  4673. elif tab_obj_name == "database_tab":
  4674. # disconnect the signals from the table widget in tab
  4675. self.tools_db_tab.ui_disconnect()
  4676. if self.tools_db_changed_flag is True:
  4677. msgbox = QtWidgets.QMessageBox()
  4678. msgbox.setText(_("One or more Tools are edited.\n"
  4679. "Do you want to update the Tools Database?"))
  4680. msgbox.setWindowTitle(_("Save Tools Database"))
  4681. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4682. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4683. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4684. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4685. msgbox.setDefaultButton(bt_yes)
  4686. msgbox.exec_()
  4687. response = msgbox.clickedButton()
  4688. if response == bt_yes:
  4689. self.tools_db_tab.on_save_tools_db()
  4690. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4691. else:
  4692. self.tools_db_changed_flag = False
  4693. self.inform.emit('')
  4694. return
  4695. self.tools_db_tab.deleteLater()
  4696. elif tab_obj_name == "text_editor_tab":
  4697. self.toggle_codeeditor = False
  4698. elif tab_obj_name == "bookmarks_tab":
  4699. self.book_dialog_tab.rebuild_actions()
  4700. self.book_dialog_tab.deleteLater()
  4701. else:
  4702. pass
  4703. # restore the coords toolbars
  4704. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4705. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4706. def on_flipy(self):
  4707. """
  4708. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4709. :return:
  4710. """
  4711. self.defaults.report_usage("on_flipy()")
  4712. obj_list = self.collection.get_selected()
  4713. xminlist = []
  4714. yminlist = []
  4715. xmaxlist = []
  4716. ymaxlist = []
  4717. if not obj_list:
  4718. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4719. else:
  4720. try:
  4721. # first get a bounding box to fit all
  4722. for obj in obj_list:
  4723. xmin, ymin, xmax, ymax = obj.bounds()
  4724. xminlist.append(xmin)
  4725. yminlist.append(ymin)
  4726. xmaxlist.append(xmax)
  4727. ymaxlist.append(ymax)
  4728. # get the minimum x,y and maximum x,y for all objects selected
  4729. xminimal = min(xminlist)
  4730. yminimal = min(yminlist)
  4731. xmaximal = max(xmaxlist)
  4732. ymaximal = max(ymaxlist)
  4733. px = 0.5 * (xminimal + xmaximal)
  4734. py = 0.5 * (yminimal + ymaximal)
  4735. # execute mirroring
  4736. for obj in obj_list:
  4737. obj.mirror('X', [px, py])
  4738. obj.plot()
  4739. self.app_obj.object_changed.emit(obj)
  4740. self.inform.emit('[success] %s' %
  4741. _("Flip on Y axis done."))
  4742. except Exception as e:
  4743. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4744. return
  4745. def on_flipx(self):
  4746. """
  4747. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4748. :return:
  4749. """
  4750. self.defaults.report_usage("on_flipx()")
  4751. obj_list = self.collection.get_selected()
  4752. xminlist = []
  4753. yminlist = []
  4754. xmaxlist = []
  4755. ymaxlist = []
  4756. if not obj_list:
  4757. self.inform.emit('[WARNING_NOTCL] %s' %
  4758. _("No object selected to Flip on X axis."))
  4759. else:
  4760. try:
  4761. # first get a bounding box to fit all
  4762. for obj in obj_list:
  4763. xmin, ymin, xmax, ymax = obj.bounds()
  4764. xminlist.append(xmin)
  4765. yminlist.append(ymin)
  4766. xmaxlist.append(xmax)
  4767. ymaxlist.append(ymax)
  4768. # get the minimum x,y and maximum x,y for all objects selected
  4769. xminimal = min(xminlist)
  4770. yminimal = min(yminlist)
  4771. xmaximal = max(xmaxlist)
  4772. ymaximal = max(ymaxlist)
  4773. px = 0.5 * (xminimal + xmaximal)
  4774. py = 0.5 * (yminimal + ymaximal)
  4775. # execute mirroring
  4776. for obj in obj_list:
  4777. obj.mirror('Y', [px, py])
  4778. obj.plot()
  4779. self.app_obj.object_changed.emit(obj)
  4780. self.inform.emit('[success] %s' %
  4781. _("Flip on X axis done."))
  4782. except Exception as e:
  4783. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4784. return
  4785. def on_rotate(self, silent=False, preset=None):
  4786. """
  4787. Executed when Options -> Rotate Selection menu entry is clicked.
  4788. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4789. :param preset: A value to be used as predefined angle for rotation.
  4790. :return:
  4791. """
  4792. self.defaults.report_usage("on_rotate()")
  4793. obj_list = self.collection.get_selected()
  4794. xminlist = []
  4795. yminlist = []
  4796. xmaxlist = []
  4797. ymaxlist = []
  4798. if not obj_list:
  4799. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4800. else:
  4801. if silent is False:
  4802. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4803. min=-360, max=360, decimals=4,
  4804. init_val=float(self.defaults['tools_transform_rotate']))
  4805. num, ok = rotatebox.get_value()
  4806. else:
  4807. num = preset
  4808. ok = True
  4809. if ok:
  4810. try:
  4811. # first get a bounding box to fit all
  4812. for obj in obj_list:
  4813. xmin, ymin, xmax, ymax = obj.bounds()
  4814. xminlist.append(xmin)
  4815. yminlist.append(ymin)
  4816. xmaxlist.append(xmax)
  4817. ymaxlist.append(ymax)
  4818. # get the minimum x,y and maximum x,y for all objects selected
  4819. xminimal = min(xminlist)
  4820. yminimal = min(yminlist)
  4821. xmaximal = max(xmaxlist)
  4822. ymaximal = max(ymaxlist)
  4823. px = 0.5 * (xminimal + xmaximal)
  4824. py = 0.5 * (yminimal + ymaximal)
  4825. for sel_obj in obj_list:
  4826. sel_obj.rotate(-float(num), point=(px, py))
  4827. sel_obj.plot()
  4828. self.app_obj.object_changed.emit(sel_obj)
  4829. self.inform.emit('[success] %s' % _("Rotation done."))
  4830. except Exception as e:
  4831. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4832. return
  4833. def on_skewx(self):
  4834. """
  4835. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4836. :return:
  4837. """
  4838. self.defaults.report_usage("on_skewx()")
  4839. obj_list = self.collection.get_selected()
  4840. xminlist = []
  4841. yminlist = []
  4842. if not obj_list:
  4843. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4844. else:
  4845. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4846. min=-360, max=360, decimals=4,
  4847. init_val=float(self.defaults['tools_transform_skew_x']))
  4848. num, ok = skewxbox.get_value()
  4849. if ok:
  4850. # first get a bounding box to fit all
  4851. for obj in obj_list:
  4852. xmin, ymin, xmax, ymax = obj.bounds()
  4853. xminlist.append(xmin)
  4854. yminlist.append(ymin)
  4855. # get the minimum x,y and maximum x,y for all objects selected
  4856. xminimal = min(xminlist)
  4857. yminimal = min(yminlist)
  4858. for obj in obj_list:
  4859. obj.skew(num, 0, point=(xminimal, yminimal))
  4860. obj.plot()
  4861. self.app_obj.object_changed.emit(obj)
  4862. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4863. def on_skewy(self):
  4864. """
  4865. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4866. :return:
  4867. """
  4868. self.defaults.report_usage("on_skewy()")
  4869. obj_list = self.collection.get_selected()
  4870. xminlist = []
  4871. yminlist = []
  4872. if not obj_list:
  4873. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4874. else:
  4875. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4876. min=-360, max=360, decimals=4,
  4877. init_val=float(self.defaults['tools_transform_skew_y']))
  4878. num, ok = skewybox.get_value()
  4879. if ok:
  4880. # first get a bounding box to fit all
  4881. for obj in obj_list:
  4882. xmin, ymin, xmax, ymax = obj.bounds()
  4883. xminlist.append(xmin)
  4884. yminlist.append(ymin)
  4885. # get the minimum x,y and maximum x,y for all objects selected
  4886. xminimal = min(xminlist)
  4887. yminimal = min(yminlist)
  4888. for obj in obj_list:
  4889. obj.skew(0, num, point=(xminimal, yminimal))
  4890. obj.plot()
  4891. self.app_obj.object_changed.emit(obj)
  4892. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4893. def on_plots_updated(self):
  4894. """
  4895. Callback used to report when the plots have changed.
  4896. Adjust axes and zooms to fit.
  4897. :return: None
  4898. """
  4899. if self.is_legacy is False:
  4900. self.plotcanvas.update()
  4901. else:
  4902. self.plotcanvas.auto_adjust_axes()
  4903. self.on_zoom_fit()
  4904. self.collection.update_view()
  4905. # self.inform.emit(_("Plots updated ..."))
  4906. def on_toolbar_replot(self):
  4907. """
  4908. Callback for toolbar button. Re-plots all objects.
  4909. :return: None
  4910. """
  4911. self.log.debug("on_toolbar_replot()")
  4912. try:
  4913. obj = self.collection.get_active()
  4914. if obj:
  4915. obj.read_form()
  4916. else:
  4917. self.on_zoom_fit()
  4918. except AttributeError as e:
  4919. log.debug("on_toolbar_replot() -> %s" % str(e))
  4920. pass
  4921. self.plot_all()
  4922. def grid_status(self):
  4923. return True if self.ui.grid_snap_btn.isChecked() else False
  4924. def populate_cmenu_grids(self):
  4925. units = self.defaults['units'].lower()
  4926. # for act in self.ui.cmenu_gridmenu.actions():
  4927. # act.triggered.disconnect()
  4928. self.ui.cmenu_gridmenu.clear()
  4929. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4930. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4931. _("Grid On/Off"))
  4932. grid_toggle.setCheckable(True)
  4933. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4934. self.ui.cmenu_gridmenu.addSeparator()
  4935. for grid in sorted_list:
  4936. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4937. "%s" % str(grid))
  4938. action.triggered.connect(self.set_grid)
  4939. self.ui.cmenu_gridmenu.addSeparator()
  4940. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4941. _("Add"))
  4942. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4943. _("Delete"))
  4944. grid_add.triggered.connect(self.on_grid_add)
  4945. grid_delete.triggered.connect(self.on_grid_delete)
  4946. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4947. def set_grid(self):
  4948. menu_action = self.sender()
  4949. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4950. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4951. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4952. def on_grid_add(self):
  4953. # ## Current application units in lower Case
  4954. units = self.defaults['units'].lower()
  4955. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4956. text=_('Enter a Grid Value:'),
  4957. min=0.0000, max=99.9999, decimals=4)
  4958. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4959. val, ok = grid_add_popup.get_value()
  4960. if ok:
  4961. if float(val) == 0:
  4962. self.inform.emit('[WARNING_NOTCL] %s' %
  4963. _("Please enter a grid value with non-zero value, in Float format."))
  4964. return
  4965. else:
  4966. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4967. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4968. self.inform.emit('[success] %s...' % _("New Grid added"))
  4969. else:
  4970. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4971. else:
  4972. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4973. def on_grid_delete(self):
  4974. # ## Current application units in lower Case
  4975. units = self.defaults['units'].lower()
  4976. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4977. text='Enter a Grid Value:',
  4978. min=0.0000, max=99.9999, decimals=4)
  4979. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4980. val, ok = grid_del_popup.get_value()
  4981. if ok:
  4982. if float(val) == 0:
  4983. self.inform.emit('[WARNING_NOTCL] %s' %
  4984. _("Please enter a grid value with non-zero value, in Float format."))
  4985. return
  4986. else:
  4987. try:
  4988. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4989. except ValueError:
  4990. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4991. return
  4992. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4993. else:
  4994. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4995. def on_shortcut_list(self):
  4996. self.defaults.report_usage("on_shortcut_list()")
  4997. # add the tab if it was closed
  4998. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4999. # delete the absolute and relative position and messages in the infobar
  5000. # self.ui.position_label.setText("")
  5001. # self.ui.rel_position_label.setText("")
  5002. # hide coordinates toolbars in the infobar while in DB
  5003. self.ui.coords_toolbar.hide()
  5004. self.ui.delta_coords_toolbar.hide()
  5005. # Switch plot_area to preferences page
  5006. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5007. # self.ui.show()
  5008. def on_select_tab(self, name):
  5009. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5010. if self.ui.splitter.sizes()[0] == 0:
  5011. self.ui.splitter.setSizes([1, 1])
  5012. else:
  5013. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5014. self.ui.splitter.setSizes([0, 1])
  5015. if name == 'project':
  5016. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5017. elif name == 'selected':
  5018. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5019. elif name == 'tool':
  5020. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5021. def on_copy_name(self):
  5022. self.defaults.report_usage("on_copy_name()")
  5023. obj = self.collection.get_active()
  5024. try:
  5025. name = obj.options["name"]
  5026. except AttributeError:
  5027. log.debug("on_copy_name() --> No object selected to copy it's name")
  5028. self.inform.emit('[WARNING_NOTCL] %s' %
  5029. _(" No object selected to copy it's name"))
  5030. return
  5031. self.clipboard.setText(name)
  5032. self.inform.emit(_("Name copied on clipboard ..."))
  5033. def on_mouse_click_over_plot(self, event):
  5034. """
  5035. Default actions are:
  5036. :param event: Contains information about the event, like which button
  5037. was clicked, the pixel coordinates and the axes coordinates.
  5038. :return: None
  5039. """
  5040. self.pos = []
  5041. if self.is_legacy is False:
  5042. event_pos = event.pos
  5043. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5044. # # Set the mouse button for panning
  5045. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5046. else:
  5047. event_pos = (event.xdata, event.ydata)
  5048. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5049. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5050. # So it can receive key presses
  5051. self.plotcanvas.native.setFocus()
  5052. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5053. if self.grid_status():
  5054. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5055. else:
  5056. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5057. try:
  5058. if event.button == 1:
  5059. # Reset here the relative coordinates so there is a new reference on the click position
  5060. if self.rel_point1 is None:
  5061. self.rel_point1 = self.pos
  5062. else:
  5063. self.rel_point2 = copy(self.rel_point1)
  5064. self.rel_point1 = self.pos
  5065. self.on_mouse_move_over_plot(event, origin_click=True)
  5066. except Exception as e:
  5067. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5068. def on_mouse_double_click_over_plot(self, event):
  5069. if event.button == 1:
  5070. self.doubleclick = True
  5071. def on_mouse_move_over_plot(self, event, origin_click=None):
  5072. """
  5073. Callback for the mouse motion event over the plot.
  5074. :param event: Contains information about the event.
  5075. :param origin_click
  5076. :return: None
  5077. """
  5078. if self.is_legacy is False:
  5079. event_pos = event.pos
  5080. if self.defaults["global_pan_button"] == '2':
  5081. pan_button = 2
  5082. else:
  5083. pan_button = 3
  5084. self.event_is_dragging = event.is_dragging
  5085. else:
  5086. event_pos = (event.xdata, event.ydata)
  5087. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5088. if self.defaults["global_pan_button"] == '2':
  5089. pan_button = 3
  5090. else:
  5091. pan_button = 2
  5092. self.event_is_dragging = self.plotcanvas.is_dragging
  5093. # So it can receive key presses but not when the Tcl Shell is active
  5094. if not self.ui.shell_dock.isVisible():
  5095. if not self.plotcanvas.native.hasFocus():
  5096. self.plotcanvas.native.setFocus()
  5097. self.pos_jump = event_pos
  5098. self.ui.popMenu.mouse_is_panning = False
  5099. if origin_click is None:
  5100. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5101. if event.button == pan_button and self.event_is_dragging == 1:
  5102. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5103. if self.ui.popMenu.popup_active:
  5104. self.ui.popMenu.popup_active = False
  5105. return
  5106. self.ui.popMenu.mouse_is_panning = True
  5107. return
  5108. if self.rel_point1 is not None:
  5109. try: # May fail in case mouse not within axes
  5110. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5111. if pos_canvas[0] is None or pos_canvas[1] is None:
  5112. return
  5113. if self.grid_status():
  5114. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5115. # Update cursor
  5116. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5117. symbol='++', edge_color=self.cursor_color_3D,
  5118. edge_width=self.defaults["global_cursor_width"],
  5119. size=self.defaults["global_cursor_size"])
  5120. else:
  5121. pos = (pos_canvas[0], pos_canvas[1])
  5122. self.dx = pos[0] - float(self.rel_point1[0])
  5123. self.dy = pos[1] - float(self.rel_point1[1])
  5124. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5125. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5126. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5127. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5128. units = self.defaults["units"].lower()
  5129. self.plotcanvas.text_hud.text = \
  5130. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5131. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5132. self.mouse = [pos[0], pos[1]]
  5133. if self.defaults['global_selection_shape'] is False:
  5134. self.selection_type = None
  5135. return
  5136. # if the mouse is moved and the LMB is clicked then the action is a selection
  5137. if self.event_is_dragging == 1 and event.button == 1:
  5138. self.delete_selection_shape()
  5139. if self.dx < 0:
  5140. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5141. face_color=self.defaults['global_alt_sel_fill'])
  5142. self.selection_type = False
  5143. elif self.dx >= 0:
  5144. self.draw_moving_selection_shape(self.pos, pos)
  5145. self.selection_type = True
  5146. else:
  5147. self.selection_type = None
  5148. else:
  5149. self.selection_type = None
  5150. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5151. if self.defaults['global_hover']:
  5152. for obj in self.collection.get_list():
  5153. try:
  5154. # select the object(s) only if it is enabled (plotted)
  5155. if obj.options['plot']:
  5156. if obj not in self.collection.get_selected():
  5157. poly_obj = Polygon(
  5158. [(obj.options['xmin'], obj.options['ymin']),
  5159. (obj.options['xmax'], obj.options['ymin']),
  5160. (obj.options['xmax'], obj.options['ymax']),
  5161. (obj.options['xmin'], obj.options['ymax'])]
  5162. )
  5163. if Point(pos).within(poly_obj):
  5164. if obj.isHovering is False:
  5165. obj.isHovering = True
  5166. obj.notHovering = True
  5167. # create the selection box around the selected object
  5168. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5169. else:
  5170. if obj.notHovering is True:
  5171. obj.notHovering = False
  5172. obj.isHovering = False
  5173. self.delete_hover_shape()
  5174. except Exception:
  5175. # the Exception here will happen if we try to select on screen and we have an
  5176. # newly (and empty) just created Geometry or Excellon object that do not have the
  5177. # xmin, xmax, ymin, ymax options.
  5178. # In this case poly_obj creation (see above) will fail
  5179. pass
  5180. except Exception as e:
  5181. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5182. self.ui.position_label.setText("")
  5183. self.ui.rel_position_label.setText("")
  5184. self.mouse = None
  5185. def on_mouse_click_release_over_plot(self, event):
  5186. """
  5187. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5188. and has been registered in ''self.__init__()''.
  5189. :param event: contains information about the event.
  5190. :return:
  5191. """
  5192. if self.is_legacy is False:
  5193. event_pos = event.pos
  5194. right_button = 2
  5195. else:
  5196. event_pos = (event.xdata, event.ydata)
  5197. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5198. right_button = 3
  5199. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5200. if self.grid_status():
  5201. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5202. else:
  5203. pos = (pos_canvas[0], pos_canvas[1])
  5204. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5205. # canvas menu
  5206. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5207. self.ui.popMenu.mouse_is_panning = False
  5208. self.cursor = QtGui.QCursor()
  5209. self.populate_cmenu_grids()
  5210. self.ui.popMenu.popup(self.cursor.pos())
  5211. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5212. # selection and then select a type of selection ("enclosing" or "touching")
  5213. if event.button == 1: # left click
  5214. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5215. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5216. if modifiers == QtCore.Qt.ShiftModifier:
  5217. # do not auto open the Project Tab
  5218. self.click_noproject = True
  5219. self.clipboard.setText(
  5220. self.defaults["global_point_clipboard_format"] %
  5221. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5222. )
  5223. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5224. return
  5225. if self.doubleclick is True:
  5226. self.doubleclick = False
  5227. if self.collection.get_selected():
  5228. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5229. if self.ui.splitter.sizes()[0] == 0:
  5230. self.ui.splitter.setSizes([1, 1])
  5231. try:
  5232. # delete the selection shape(S) as it may be in the way
  5233. self.delete_selection_shape()
  5234. self.delete_hover_shape()
  5235. except Exception as e:
  5236. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5237. return
  5238. else:
  5239. # WORKAROUND for LEGACY MODE
  5240. if self.is_legacy is True:
  5241. # if there is no move on canvas then we have no dragging selection
  5242. if self.dx == 0 or self.dy == 0:
  5243. self.selection_type = None
  5244. if self.selection_type is not None:
  5245. try:
  5246. self.selection_area_handler(self.pos, pos, self.selection_type)
  5247. self.selection_type = None
  5248. except Exception as e:
  5249. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5250. return
  5251. else:
  5252. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5253. if key_modifier == QtCore.Qt.ShiftModifier:
  5254. mod_key = 'Shift'
  5255. elif key_modifier == QtCore.Qt.ControlModifier:
  5256. mod_key = 'Control'
  5257. else:
  5258. mod_key = None
  5259. try:
  5260. if self.command_active is None:
  5261. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5262. # deselect, and if it's not selected then it will be selected
  5263. # If there is no active command (self.command_active is None) then we check if we clicked
  5264. # on a object by checking the bounding limits against mouse click position
  5265. if mod_key == self.defaults["global_mselect_key"]:
  5266. self.select_objects(key='multisel')
  5267. else:
  5268. # If there is no active command (self.command_active is None) then we check if
  5269. # we clicked on a object by checking the bounding limits against mouse click position
  5270. self.select_objects()
  5271. self.delete_hover_shape()
  5272. except Exception as e:
  5273. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5274. return
  5275. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5276. """
  5277. :param start_pos: mouse position when the selection LMB click was done
  5278. :param end_pos: mouse position when the left mouse button is released
  5279. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5280. :return:
  5281. """
  5282. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5283. # delete previous selection shape
  5284. self.delete_selection_shape()
  5285. # make all objects inactive
  5286. self.collection.set_all_inactive()
  5287. for obj in self.collection.get_list():
  5288. try:
  5289. # select the object(s) only if it is enabled (plotted)
  5290. if obj.options['plot']:
  5291. # it's a line without area
  5292. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5293. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5294. # it's a geometry with area
  5295. else:
  5296. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5297. (obj.options['xmax'], obj.options['ymin']),
  5298. (obj.options['xmax'], obj.options['ymax']),
  5299. (obj.options['xmin'], obj.options['ymax'])])
  5300. if poly_obj.is_empty or not poly_obj.is_valid:
  5301. continue
  5302. if sel_type is True:
  5303. if poly_obj.within(poly_selection):
  5304. # create the selection box around the selected object
  5305. if self.defaults['global_selection_shape'] is True:
  5306. self.draw_selection_shape(obj)
  5307. self.collection.set_active(obj.options['name'])
  5308. else:
  5309. if poly_selection.intersects(poly_obj):
  5310. # create the selection box around the selected object
  5311. if self.defaults['global_selection_shape'] is True:
  5312. self.draw_selection_shape(obj)
  5313. self.collection.set_active(obj.options['name'])
  5314. obj.selection_shape_drawn = True
  5315. except Exception as e:
  5316. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5317. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5318. # In this case poly_obj creation (see above) will fail
  5319. log.debug("App.selection_area_handler() --> %s" % str(e))
  5320. def select_objects(self, key=None):
  5321. """
  5322. Will select objects clicked on canvas
  5323. :param key: for future use in cumulative selection
  5324. :return:
  5325. """
  5326. # list where we store the overlapped objects under our mouse left click position
  5327. if key is None:
  5328. self.objects_under_the_click_list = []
  5329. # Populate the list with the overlapped objects on the click position
  5330. curr_x, curr_y = self.pos
  5331. for obj in self.all_objects_list:
  5332. # ScriptObject and DocumentObject objects can't be selected
  5333. if obj.kind == 'script' or obj.kind == 'document':
  5334. continue
  5335. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5336. continue
  5337. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5338. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5339. if obj.options['name'] not in self.objects_under_the_click_list:
  5340. if obj.options['plot']:
  5341. # add objects to the objects_under_the_click list only if the object is plotted
  5342. # (active and not disabled)
  5343. self.objects_under_the_click_list.append(obj.options['name'])
  5344. try:
  5345. if self.objects_under_the_click_list:
  5346. curr_sel_obj = self.collection.get_active()
  5347. # case when there is only an object under the click and we toggle it
  5348. if len(self.objects_under_the_click_list) == 1:
  5349. if curr_sel_obj is None:
  5350. self.collection.set_active(self.objects_under_the_click_list[0])
  5351. curr_sel_obj = self.collection.get_active()
  5352. # create the selection box around the selected object
  5353. if self.defaults['global_selection_shape'] is True:
  5354. self.draw_selection_shape(curr_sel_obj)
  5355. curr_sel_obj.selection_shape_drawn = True
  5356. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5357. self.collection.on_objects_selection(False)
  5358. self.delete_selection_shape()
  5359. curr_sel_obj.selection_shape_drawn = False
  5360. self.collection.set_active(self.objects_under_the_click_list[0])
  5361. curr_sel_obj = self.collection.get_active()
  5362. # create the selection box around the selected object
  5363. if self.defaults['global_selection_shape'] is True:
  5364. self.draw_selection_shape(curr_sel_obj)
  5365. curr_sel_obj.selection_shape_drawn = True
  5366. self.selected_message(curr_sel_obj=curr_sel_obj)
  5367. elif curr_sel_obj.selection_shape_drawn is False:
  5368. if self.defaults['global_selection_shape'] is True:
  5369. self.draw_selection_shape(curr_sel_obj)
  5370. curr_sel_obj.selection_shape_drawn = True
  5371. else:
  5372. self.collection.on_objects_selection(False)
  5373. self.delete_selection_shape()
  5374. if self.call_source != 'app':
  5375. self.call_source = 'app'
  5376. self.selected_message(curr_sel_obj=curr_sel_obj)
  5377. else:
  5378. # If there is no selected object
  5379. # make active the first element of the overlapped objects list
  5380. if self.collection.get_active() is None:
  5381. self.collection.set_active(self.objects_under_the_click_list[0])
  5382. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5383. name_sel_obj = self.collection.get_active().options['name']
  5384. # In case that there is a selected object but it is not in the overlapped object list
  5385. # make that object inactive and activate the first element in the overlapped object list
  5386. if name_sel_obj not in self.objects_under_the_click_list:
  5387. self.collection.set_inactive(name_sel_obj)
  5388. name_sel_obj = self.objects_under_the_click_list[0]
  5389. self.collection.set_active(name_sel_obj)
  5390. else:
  5391. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5392. self.collection.set_all_inactive()
  5393. self.collection.set_active(
  5394. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5395. curr_sel_obj = self.collection.get_active()
  5396. # delete the possible selection box around a possible selected object
  5397. self.delete_selection_shape()
  5398. curr_sel_obj.selection_shape_drawn = False
  5399. # create the selection box around the selected object
  5400. if self.defaults['global_selection_shape'] is True:
  5401. self.draw_selection_shape(curr_sel_obj)
  5402. curr_sel_obj.selection_shape_drawn = True
  5403. self.selected_message(curr_sel_obj=curr_sel_obj)
  5404. else:
  5405. # deselect everything
  5406. self.collection.on_objects_selection(False)
  5407. # delete the possible selection box around a possible selected object
  5408. self.delete_selection_shape()
  5409. for o in self.collection.get_list():
  5410. o.selection_shape_drawn = False
  5411. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5412. # only when working on App
  5413. if self.call_source == 'app':
  5414. if self.click_noproject is False:
  5415. # if the Tool Tab is in focus don't change focus to Project Tab
  5416. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5417. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5418. else:
  5419. # restore auto open the Project Tab
  5420. self.click_noproject = False
  5421. # delete any text in the status bar, implicitly the last object name that was selected
  5422. # self.inform.emit("")
  5423. else:
  5424. self.call_source = 'app'
  5425. except Exception as e:
  5426. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5427. def selected_message(self, curr_sel_obj):
  5428. if curr_sel_obj:
  5429. if curr_sel_obj.kind == 'gerber':
  5430. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5431. color='green',
  5432. name=str(curr_sel_obj.options['name']),
  5433. tx=_("selected"))
  5434. )
  5435. elif curr_sel_obj.kind == 'excellon':
  5436. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5437. color='brown',
  5438. name=str(curr_sel_obj.options['name']),
  5439. tx=_("selected"))
  5440. )
  5441. elif curr_sel_obj.kind == 'cncjob':
  5442. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5443. color='blue',
  5444. name=str(curr_sel_obj.options['name']),
  5445. tx=_("selected"))
  5446. )
  5447. elif curr_sel_obj.kind == 'geometry':
  5448. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5449. color='red',
  5450. name=str(curr_sel_obj.options['name']),
  5451. tx=_("selected"))
  5452. )
  5453. def delete_hover_shape(self):
  5454. self.hover_shapes.clear()
  5455. self.hover_shapes.redraw()
  5456. def draw_hover_shape(self, sel_obj, color=None):
  5457. """
  5458. :param sel_obj: The object for which the hover shape must be drawn
  5459. :param color: The color of the hover shape
  5460. :return: None
  5461. """
  5462. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5463. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5464. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5465. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5466. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5467. if self.defaults['units'].upper() == 'MM':
  5468. hover_rect = hover_rect.buffer(-0.1)
  5469. hover_rect = hover_rect.buffer(0.2)
  5470. else:
  5471. hover_rect = hover_rect.buffer(-0.00393)
  5472. hover_rect = hover_rect.buffer(0.00787)
  5473. # if color:
  5474. # face = Color(color)
  5475. # face.alpha = 0.2
  5476. # outline = Color(color, alpha=0.8)
  5477. # else:
  5478. # face = Color(self.defaults['global_sel_fill'])
  5479. # face.alpha = 0.2
  5480. # outline = self.defaults['global_sel_line']
  5481. if color:
  5482. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5483. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5484. else:
  5485. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5486. outline = self.defaults['global_sel_line']
  5487. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5488. if self.is_legacy is True:
  5489. self.hover_shapes.redraw()
  5490. def delete_selection_shape(self):
  5491. self.move_tool.sel_shapes.clear()
  5492. self.move_tool.sel_shapes.redraw()
  5493. def draw_selection_shape(self, sel_obj, color=None):
  5494. """
  5495. Will draw a selection shape around the selected object.
  5496. :param sel_obj: The object for which the selection shape must be drawn
  5497. :param color: The color for the selection shape.
  5498. :return: None
  5499. """
  5500. if sel_obj is None:
  5501. return
  5502. # it's a line without area
  5503. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5504. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5505. # it's a geometry with area
  5506. else:
  5507. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5508. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5509. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5510. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5511. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5512. b_sel_rect = None
  5513. try:
  5514. if self.defaults['units'].upper() == 'MM':
  5515. b_sel_rect = sel_rect.buffer(-0.1)
  5516. b_sel_rect = b_sel_rect.buffer(0.2)
  5517. else:
  5518. b_sel_rect = sel_rect.buffer(-0.00393)
  5519. b_sel_rect = b_sel_rect.buffer(0.00787)
  5520. except Exception:
  5521. pass
  5522. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5523. b_sel_rect = sel_rect
  5524. if color:
  5525. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5526. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5527. else:
  5528. if self.is_legacy is False:
  5529. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5530. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5531. else:
  5532. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5533. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5534. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5535. color=outline,
  5536. face_color=face,
  5537. update=True,
  5538. layer=0,
  5539. tolerance=None))
  5540. if self.is_legacy is True:
  5541. self.move_tool.sel_shapes.redraw()
  5542. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5543. """
  5544. Will draw a selection shape when dragging mouse on canvas.
  5545. :param old_coords: Old coordinates
  5546. :param coords: New coordinates
  5547. :param kwargs: Keyword arguments
  5548. :return:
  5549. """
  5550. if 'color' in kwargs:
  5551. color = kwargs['color']
  5552. else:
  5553. color = self.defaults['global_sel_line']
  5554. if 'face_color' in kwargs:
  5555. face_color = kwargs['face_color']
  5556. else:
  5557. face_color = self.defaults['global_sel_fill']
  5558. if 'face_alpha' in kwargs:
  5559. face_alpha = kwargs['face_alpha']
  5560. else:
  5561. face_alpha = 0.3
  5562. x0, y0 = old_coords
  5563. x1, y1 = coords
  5564. pt1 = (x0, y0)
  5565. pt2 = (x1, y0)
  5566. pt3 = (x1, y1)
  5567. pt4 = (x0, y1)
  5568. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5569. # color_t = Color(face_color)
  5570. # color_t.alpha = face_alpha
  5571. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5572. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5573. layer=0, tolerance=None)
  5574. if self.is_legacy is True:
  5575. self.move_tool.sel_shapes.redraw()
  5576. def obj_properties(self):
  5577. """
  5578. Will launch the object Properties Tool
  5579. :return:
  5580. """
  5581. self.defaults.report_usage("obj_properties()")
  5582. self.properties_tool.run(toggle=False)
  5583. def on_project_context_save(self):
  5584. """
  5585. Wrapper, will save the object function of it's type
  5586. :return:
  5587. """
  5588. sel_objects = self.collection.get_selected()
  5589. len_objects = len(sel_objects)
  5590. cnt = 0
  5591. if len_objects > 1:
  5592. for o in sel_objects:
  5593. if o.kind == 'cncjob':
  5594. cnt += 1
  5595. if len_objects == cnt:
  5596. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5597. _filter_ = self.defaults['cncjob_save_filters'] + \
  5598. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5599. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5600. try:
  5601. filename, _f = FCFileSaveDialog.get_saved_filename(
  5602. caption=_("Export Code ..."),
  5603. directory=dir_file_to_save,
  5604. ext_filter=_filter_
  5605. )
  5606. except TypeError:
  5607. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5608. ext_filter=_filter_)
  5609. filename = filename.rpartition('/')[0]
  5610. for ob in sel_objects:
  5611. ob.read_form()
  5612. fname = '%s/%s' % (filename, ob.options['name'])
  5613. ob.export_gcode_handler(fname, is_gcode=True)
  5614. return
  5615. obj = self.collection.get_active()
  5616. if type(obj) == GeometryObject:
  5617. self.on_file_exportdxf()
  5618. elif type(obj) == ExcellonObject:
  5619. self.on_file_saveexcellon()
  5620. elif type(obj) == CNCJobObject:
  5621. obj.on_exportgcode_button_click()
  5622. elif type(obj) == GerberObject:
  5623. self.on_file_savegerber()
  5624. elif type(obj) == ScriptObject:
  5625. self.on_file_savescript()
  5626. elif type(obj) == DocumentObject:
  5627. self.on_file_savedocument()
  5628. def obj_move(self):
  5629. """
  5630. Callback for the Move menu entry in various Context Menu's.
  5631. :return:
  5632. """
  5633. self.defaults.report_usage("obj_move()")
  5634. self.move_tool.run(toggle=False)
  5635. # ###############################################################################################################
  5636. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5637. # ###############################################################################################################
  5638. def init_code_editor(self, name):
  5639. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5640. # add the tab if it was closed
  5641. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5642. self.text_editor_tab.setObjectName('text_editor_tab')
  5643. # delete the absolute and relative position and messages in the infobar
  5644. # self.ui.position_label.setText("")
  5645. # self.ui.rel_position_label.setText("")
  5646. # hide coordinates toolbars in the infobar while in DB
  5647. self.ui.coords_toolbar.hide()
  5648. self.ui.delta_coords_toolbar.hide()
  5649. self.toggle_codeeditor = True
  5650. self.text_editor_tab.code_editor.completer_enable = False
  5651. self.text_editor_tab.buttonRun.hide()
  5652. # make sure to keep a reference to the code editor
  5653. self.reference_code_editor = self.text_editor_tab.code_editor
  5654. # Switch plot_area to CNCJob tab
  5655. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5656. def on_view_source(self):
  5657. """
  5658. Called when the user wants to see the source file of the selected object
  5659. :return:
  5660. """
  5661. try:
  5662. obj = self.collection.get_active()
  5663. except Exception as e:
  5664. log.debug("App.on_view_source() --> %s" % str(e))
  5665. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5666. return 'fail'
  5667. if obj is None:
  5668. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5669. return 'fail'
  5670. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5671. self.proc_container.view.set_busy(_("Loading..."))
  5672. flt = "All Files (*.*)"
  5673. if obj.kind == 'gerber':
  5674. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5675. elif obj.kind == 'excellon':
  5676. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5677. elif obj.kind == 'cncjob':
  5678. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5679. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5680. # add the tab if it was closed
  5681. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5682. self.source_editor_tab.setObjectName('source_editor_tab')
  5683. # delete the absolute and relative position and messages in the infobar
  5684. # self.ui.position_label.setText("")
  5685. # self.ui.rel_position_label.setText("")
  5686. # hide coordinates toolbars in the infobar while in DB
  5687. self.ui.coords_toolbar.hide()
  5688. self.ui.delta_coords_toolbar.hide()
  5689. self.source_editor_tab.code_editor.completer_enable = False
  5690. self.source_editor_tab.buttonRun.hide()
  5691. # Switch plot_area to CNCJob tab
  5692. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5693. try:
  5694. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5695. except TypeError:
  5696. pass
  5697. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5698. try:
  5699. self.source_editor_tab.buttonSave.clicked.disconnect()
  5700. except TypeError:
  5701. pass
  5702. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5703. # then append the text from GCode to the text editor
  5704. if obj.kind == 'cncjob':
  5705. try:
  5706. file = obj.export_gcode(to_file=True)
  5707. if file == 'fail':
  5708. return 'fail'
  5709. except AttributeError:
  5710. self.inform.emit('[WARNING_NOTCL] %s' %
  5711. _("There is no selected object for which to see it's source file code."))
  5712. return 'fail'
  5713. else:
  5714. try:
  5715. file = StringIO(obj.source_file)
  5716. except (AttributeError, TypeError):
  5717. self.inform.emit('[WARNING_NOTCL] %s' %
  5718. _("There is no selected object for which to see it's source file code."))
  5719. return 'fail'
  5720. self.source_editor_tab.t_frame.hide()
  5721. try:
  5722. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5723. except Exception as e:
  5724. log.debug('App.on_view_source() -->%s' % str(e))
  5725. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5726. return
  5727. self.source_editor_tab.t_frame.show()
  5728. self.proc_container.view.set_idle()
  5729. # self.ui.show()
  5730. def on_toggle_code_editor(self):
  5731. self.defaults.report_usage("on_toggle_code_editor()")
  5732. if self.toggle_codeeditor is False:
  5733. self.init_code_editor(name=_("Code Editor"))
  5734. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5735. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5736. self.text_editor_tab.buttonSave.clicked.disconnect()
  5737. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5738. else:
  5739. for idx in range(self.ui.plot_tab_area.count()):
  5740. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5741. self.ui.plot_tab_area.closeTab(idx)
  5742. break
  5743. self.toggle_codeeditor = False
  5744. def on_code_editor_close(self):
  5745. self.toggle_codeeditor = False
  5746. def goto_text_line(self):
  5747. """
  5748. Will scroll a text to the specified text line.
  5749. :return: None
  5750. """
  5751. dia_box = Dialog_box(title=_("Go to Line ..."),
  5752. label=_("Line:"),
  5753. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5754. initial_text='')
  5755. try:
  5756. line = int(dia_box.location) - 1
  5757. except (ValueError, TypeError):
  5758. line = 0
  5759. if dia_box.ok:
  5760. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5761. # at the top of the window
  5762. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5763. # get the document() of the AppTextEditor
  5764. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5765. # create a Text Cursor based on the searched line
  5766. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5767. # set cursor of the code editor with the cursor at the searcehd line
  5768. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5769. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5770. """
  5771. Re-generates all plots from all objects.
  5772. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5773. :param muted: if True don't print messages
  5774. :param use_thread: if True will use threading for plotting the objects
  5775. :return: None
  5776. """
  5777. self.log.debug("Plot_all()")
  5778. if muted is not True:
  5779. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5780. for plot_obj in self.collection.get_list():
  5781. def worker_task(obj):
  5782. with self.proc_container.new("Plotting"):
  5783. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5784. if fit_view is True:
  5785. self.app_obj.object_plotted.emit(obj)
  5786. if use_thread is True:
  5787. # Send to worker
  5788. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5789. else:
  5790. worker_task(plot_obj)
  5791. def register_folder(self, filename):
  5792. """
  5793. Register the last folder used by the app to open something
  5794. :param filename: the last folder is extracted from the filename
  5795. :return: None
  5796. """
  5797. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5798. def register_save_folder(self, filename):
  5799. """
  5800. Register the last folder used by the app to save something
  5801. :param filename: the last folder is extracted from the filename
  5802. :return: None
  5803. """
  5804. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5805. # def set_progress_bar(self, percentage, text=""):
  5806. # """
  5807. # Set a progress bar to a value (percentage)
  5808. #
  5809. # :param percentage: Value set to the progressbar
  5810. # :param text: Not used
  5811. # :return: None
  5812. # """
  5813. # self.ui.progress_bar.setValue(int(percentage))
  5814. def setup_recent_items(self):
  5815. """
  5816. Setup a dictionary with the recent files accessed, organized by type
  5817. :return:
  5818. """
  5819. icons = {
  5820. "gerber": self.resource_location + "/flatcam_icon16.png",
  5821. "excellon": self.resource_location + "/drill16.png",
  5822. 'geometry': self.resource_location + "/geometry16.png",
  5823. "cncjob": self.resource_location + "/cnc16.png",
  5824. "script": self.resource_location + "/script_new24.png",
  5825. "document": self.resource_location + "/notes16_1.png",
  5826. "project": self.resource_location + "/project16.png",
  5827. "svg": self.resource_location + "/geometry16.png",
  5828. "dxf": self.resource_location + "/dxf16.png",
  5829. "pdf": self.resource_location + "/pdf32.png",
  5830. "image": self.resource_location + "/image16.png"
  5831. }
  5832. try:
  5833. image_opener = self.image_tool.import_image
  5834. except AttributeError:
  5835. image_opener = None
  5836. openers = {
  5837. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5838. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5839. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5840. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5841. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5842. "document": None,
  5843. 'project': self.f_handlers.open_project,
  5844. 'svg': self.f_handlers.import_svg,
  5845. 'dxf': self.f_handlers.import_dxf,
  5846. 'image': image_opener,
  5847. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5848. }
  5849. # Open recent file for files
  5850. try:
  5851. f = open(self.data_path + '/recent.json')
  5852. except IOError:
  5853. App.log.error("Failed to load recent item list.")
  5854. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5855. return
  5856. try:
  5857. self.recent = json.load(f)
  5858. except json.errors.JSONDecodeError:
  5859. App.log.error("Failed to parse recent item list.")
  5860. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5861. f.close()
  5862. return
  5863. f.close()
  5864. # Open recent file for projects
  5865. try:
  5866. fp = open(self.data_path + '/recent_projects.json')
  5867. except IOError:
  5868. App.log.error("Failed to load recent project item list.")
  5869. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5870. return
  5871. try:
  5872. self.recent_projects = json.load(fp)
  5873. except json.errors.JSONDecodeError:
  5874. App.log.error("Failed to parse recent project item list.")
  5875. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5876. fp.close()
  5877. return
  5878. fp.close()
  5879. # Closure needed to create callbacks in a loop.
  5880. # Otherwise late binding occurs.
  5881. def make_callback(func, fname):
  5882. def opener():
  5883. func(fname)
  5884. return opener
  5885. def reset_recent_files():
  5886. # Reset menu
  5887. self.ui.recent.clear()
  5888. self.recent = []
  5889. try:
  5890. ff = open(self.data_path + '/recent.json', 'w')
  5891. except IOError:
  5892. App.log.error("Failed to open recent items file for writing.")
  5893. return
  5894. json.dump(self.recent, ff)
  5895. def reset_recent_projects():
  5896. # Reset menu
  5897. self.ui.recent_projects.clear()
  5898. self.recent_projects = []
  5899. try:
  5900. frp = open(self.data_path + '/recent_projects.json', 'w')
  5901. except IOError:
  5902. App.log.error("Failed to open recent projects items file for writing.")
  5903. return
  5904. json.dump(self.recent, frp)
  5905. # Reset menu
  5906. self.ui.recent.clear()
  5907. self.ui.recent_projects.clear()
  5908. # Create menu items for projects
  5909. for recent in self.recent_projects:
  5910. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5911. if recent['kind'] == 'project':
  5912. try:
  5913. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5914. # Attach callback
  5915. o = make_callback(openers[recent["kind"]], recent['filename'])
  5916. action.triggered.connect(o)
  5917. self.ui.recent_projects.addAction(action)
  5918. except KeyError:
  5919. App.log.error("Unsupported file type: %s" % recent["kind"])
  5920. # Last action in Recent Files menu is one that Clear the content
  5921. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5922. (_("Clear Recent projects")), self)
  5923. clear_action_proj.triggered.connect(reset_recent_projects)
  5924. self.ui.recent_projects.addSeparator()
  5925. self.ui.recent_projects.addAction(clear_action_proj)
  5926. # Create menu items for files
  5927. for recent in self.recent:
  5928. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5929. if recent['kind'] != 'project':
  5930. try:
  5931. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5932. # Attach callback
  5933. o = make_callback(openers[recent["kind"]], recent['filename'])
  5934. action.triggered.connect(o)
  5935. self.ui.recent.addAction(action)
  5936. except KeyError:
  5937. App.log.error("Unsupported file type: %s" % recent["kind"])
  5938. # Last action in Recent Files menu is one that Clear the content
  5939. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5940. (_("Clear Recent files")), self)
  5941. clear_action.triggered.connect(reset_recent_files)
  5942. self.ui.recent.addSeparator()
  5943. self.ui.recent.addAction(clear_action)
  5944. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5945. # self.ui.menufilerecent.set_submenu(recent_menu)
  5946. # recent_menu.show_all()
  5947. # self.ui.recent.show()
  5948. self.log.debug("Recent items list has been populated.")
  5949. def on_properties_tab_click(self, index):
  5950. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  5951. self.setup_default_properties_tab()
  5952. def setup_default_properties_tab(self):
  5953. """
  5954. Default text for the Properties tab when is not taken by the Object UI.
  5955. :return:
  5956. """
  5957. # label = QtWidgets.QLabel("Choose an item from Project")
  5958. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5959. # sel_title = QtWidgets.QTextEdit()
  5960. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5961. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5962. #
  5963. # f_settings = QSettings("Open Source", "FlatCAM")
  5964. # if f_settings.contains("notebook_font_size"):
  5965. # fsize = f_settings.value('notebook_font_size', type=int)
  5966. # else:
  5967. # fsize = 12
  5968. #
  5969. # tsize = fsize + int(fsize / 2)
  5970. #
  5971. # selected_text = ''
  5972. #
  5973. # sel_title.setText(selected_text)
  5974. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5975. # Tree Widget
  5976. d_properties_tw = FCTree(columns=2)
  5977. d_properties_tw.setObjectName("default_properties")
  5978. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5979. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  5980. root = d_properties_tw.invisibleRootItem()
  5981. font = QtGui.QFont()
  5982. font.setBold(True)
  5983. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  5984. # main Items categories
  5985. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  5986. d_properties_tw.addChild(parent=general_cat,
  5987. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  5988. d_properties_tw.addChild(parent=general_cat,
  5989. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  5990. d_properties_tw.addChild(parent=general_cat,
  5991. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  5992. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  5993. d_properties_tw.addChild(parent=grid_cat,
  5994. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  5995. column1=True)
  5996. d_properties_tw.addChild(parent=grid_cat,
  5997. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  5998. column1=True)
  5999. d_properties_tw.addChild(parent=grid_cat,
  6000. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6001. column1=True)
  6002. d_properties_tw.addChild(parent=grid_cat,
  6003. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6004. column1=True)
  6005. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6006. d_properties_tw.addChild(parent=canvas_cat,
  6007. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6008. column1=True)
  6009. d_properties_tw.addChild(parent=canvas_cat,
  6010. title=['%s:' % _("Workspace active"),
  6011. '%s' % str(self.defaults['global_workspace'])],
  6012. column1=True)
  6013. d_properties_tw.addChild(parent=canvas_cat,
  6014. title=['%s:' % _("Workspace size"),
  6015. '%s' % str(self.defaults['global_workspaceT'])],
  6016. column1=True)
  6017. d_properties_tw.addChild(parent=canvas_cat,
  6018. title=['%s:' % _("Workspace orientation"),
  6019. '%s' % _("Portrait") if self.defaults[
  6020. 'global_workspace_orientation'] == 'p' else
  6021. _("Landscape")],
  6022. column1=True)
  6023. d_properties_tw.addChild(parent=canvas_cat,
  6024. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6025. column1=True)
  6026. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6027. def setup_obj_classes(self):
  6028. """
  6029. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6030. class.
  6031. :return: None
  6032. """
  6033. FlatCAMObj.app = self
  6034. ObjectCollection.app = self
  6035. Gerber.app = self
  6036. Excellon.app = self
  6037. Geometry.app = self
  6038. CNCjob.app = self
  6039. FCProcess.app = self
  6040. FCProcessContainer.app = self
  6041. OptionsGroupUI.app = self
  6042. def version_check(self):
  6043. """
  6044. Checks for the latest version of the program. Alerts the
  6045. user if theirs is outdated. This method is meant to be run
  6046. in a separate thread.
  6047. :return: None
  6048. """
  6049. self.log.debug("version_check()")
  6050. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6051. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6052. App.version_url,
  6053. str(self.defaults['global_serial']),
  6054. str(self.version),
  6055. str(self.os),
  6056. urllib.parse.urlencode(self.defaults["global_stats"])
  6057. )
  6058. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6059. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6060. # urllib.parse.urlencode(self.defaults["global_stats"])
  6061. else:
  6062. # no_stats dict; just so it won't break things on website
  6063. no_ststs_dict = {}
  6064. no_ststs_dict["global_ststs"] = {}
  6065. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6066. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6067. App.log.debug("Checking for updates @ %s" % full_url)
  6068. # ## Get the data
  6069. try:
  6070. f = urllib.request.urlopen(full_url)
  6071. except Exception:
  6072. # App.log.warning("Failed checking for latest version. Could not connect.")
  6073. self.log.warning("Failed checking for latest version. Could not connect.")
  6074. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6075. return
  6076. try:
  6077. data = json.load(f)
  6078. except Exception as e:
  6079. App.log.error("Could not parse information about latest version.")
  6080. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6081. App.log.debug("json.load(): %s" % str(e))
  6082. f.close()
  6083. return
  6084. f.close()
  6085. # ## Latest version?
  6086. if self.version >= data["version"]:
  6087. App.log.debug("FlatCAM is up to date!")
  6088. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6089. return
  6090. App.log.debug("Newer version available.")
  6091. self.message.emit(
  6092. _("Newer Version Available"),
  6093. '%s<br><br>><b>%s</b><br>%s' % (
  6094. _("There is a newer version of FlatCAM available for download:"),
  6095. str(data["name"]),
  6096. str(data["message"])
  6097. ),
  6098. _("info")
  6099. )
  6100. def on_plotcanvas_setup(self, container=None):
  6101. """
  6102. This is doing the setup for the plot area (canvas).
  6103. :param container: QT Widget where to install the canvas
  6104. :return: None
  6105. """
  6106. if container:
  6107. plot_container = container
  6108. else:
  6109. plot_container = self.ui.right_layout
  6110. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6111. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6112. self.is_legacy = True
  6113. self.defaults["global_graphic_engine"] = "2D"
  6114. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6115. else:
  6116. try:
  6117. self.plotcanvas = PlotCanvas(plot_container, self)
  6118. except Exception as er:
  6119. msg_txt = traceback.format_exc()
  6120. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6121. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6122. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6123. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6124. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6125. msg += msg_txt
  6126. self.inform.emit(msg)
  6127. return 'fail'
  6128. # So it can receive key presses
  6129. self.plotcanvas.native.setFocus()
  6130. if self.is_legacy is False:
  6131. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6132. # Set the mouse button for panning
  6133. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6134. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6135. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6136. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6137. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6138. # Keys over plot enabled
  6139. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6140. if self.defaults['global_cursor_type'] == 'small':
  6141. self.app_cursor = self.plotcanvas.new_cursor()
  6142. else:
  6143. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6144. if self.ui.grid_snap_btn.isChecked():
  6145. self.app_cursor.enabled = True
  6146. else:
  6147. self.app_cursor.enabled = False
  6148. if self.is_legacy is False:
  6149. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6150. else:
  6151. # will use the default Matplotlib axes
  6152. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6153. def on_zoom_fit(self):
  6154. """
  6155. Callback for zoom-fit request. This can be either from the corresponding
  6156. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6157. with axes limits from the geometry bounds of all objects.
  6158. :return: None
  6159. """
  6160. if self.is_legacy is False:
  6161. self.plotcanvas.fit_view()
  6162. else:
  6163. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6164. width = xmax - xmin
  6165. height = ymax - ymin
  6166. xmin -= 0.05 * width
  6167. xmax += 0.05 * width
  6168. ymin -= 0.05 * height
  6169. ymax += 0.05 * height
  6170. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6171. def on_zoom_in(self):
  6172. """
  6173. Callback for zoom-in request.
  6174. :return:
  6175. """
  6176. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6177. def on_zoom_out(self):
  6178. """
  6179. Callback for zoom-out request.
  6180. :return:
  6181. """
  6182. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6183. def disable_all_plots(self):
  6184. self.defaults.report_usage("disable_all_plots()")
  6185. self.disable_plots(self.collection.get_list())
  6186. self.inform.emit('[success] %s' % _("All plots disabled."))
  6187. def disable_other_plots(self):
  6188. self.defaults.report_usage("disable_other_plots()")
  6189. self.disable_plots(self.collection.get_non_selected())
  6190. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6191. def enable_all_plots(self):
  6192. self.defaults.report_usage("enable_all_plots()")
  6193. self.enable_plots(self.collection.get_list())
  6194. self.inform.emit('[success] %s' % _("All plots enabled."))
  6195. def enable_other_plots(self):
  6196. self.defaults.report_usage("enable_other_plots()")
  6197. self.enable_plots(self.collection.get_non_selected())
  6198. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6199. def on_enable_sel_plots(self):
  6200. log.debug("App.on_enable_sel_plot()")
  6201. object_list = self.collection.get_selected()
  6202. self.enable_plots(objects=object_list)
  6203. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6204. def on_disable_sel_plots(self):
  6205. log.debug("App.on_disable_sel_plot()")
  6206. # self.inform.emit(_("Disabling plots ..."))
  6207. object_list = self.collection.get_selected()
  6208. self.disable_plots(objects=object_list)
  6209. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6210. def enable_plots(self, objects):
  6211. """
  6212. Enable plots
  6213. :param objects: list of Objects to be enabled
  6214. :return:
  6215. """
  6216. log.debug("Enabling plots ...")
  6217. # self.inform.emit(_("Working ..."))
  6218. for obj in objects:
  6219. if obj.options['plot'] is False:
  6220. obj.options.set_change_callback(lambda x: None)
  6221. obj.options['plot'] = True
  6222. try:
  6223. # only the Gerber obj has on_plot_cb_click() method
  6224. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6225. # disable this cb while disconnected,
  6226. # in case the operation takes time the user is not allowed to change it
  6227. obj.ui.plot_cb.setDisabled(True)
  6228. except AttributeError:
  6229. pass
  6230. obj.set_form_item("plot")
  6231. try:
  6232. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6233. obj.ui.plot_cb.setDisabled(False)
  6234. except AttributeError:
  6235. pass
  6236. obj.options.set_change_callback(obj.on_options_change)
  6237. def worker_task(objs):
  6238. with self.proc_container.new(_("Enabling plots ...")):
  6239. for plot_obj in objs:
  6240. # obj.options['plot'] = True
  6241. if isinstance(plot_obj, CNCJobObject):
  6242. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6243. else:
  6244. plot_obj.plot(visible=True)
  6245. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6246. def disable_plots(self, objects):
  6247. """
  6248. Disables plots
  6249. :param objects: list of Objects to be disabled
  6250. :return:
  6251. """
  6252. log.debug("Disabling plots ...")
  6253. # self.inform.emit(_("Working ..."))
  6254. for obj in objects:
  6255. if obj.options['plot'] is True:
  6256. obj.options.set_change_callback(lambda x: None)
  6257. obj.options['plot'] = False
  6258. try:
  6259. # only the Gerber obj has on_plot_cb_click() method
  6260. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6261. obj.ui.plot_cb.setDisabled(True)
  6262. except AttributeError:
  6263. pass
  6264. obj.set_form_item("plot")
  6265. try:
  6266. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6267. obj.ui.plot_cb.setDisabled(False)
  6268. except AttributeError:
  6269. pass
  6270. obj.options.set_change_callback(obj.on_options_change)
  6271. try:
  6272. self.delete_selection_shape()
  6273. except Exception as e:
  6274. log.debug("App.disable_plots() --> %s" % str(e))
  6275. def worker_task(objs):
  6276. with self.proc_container.new(_("Disabling plots ...")):
  6277. for plot_obj in objs:
  6278. # obj.options['plot'] = True
  6279. if isinstance(plot_obj, CNCJobObject):
  6280. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6281. else:
  6282. plot_obj.plot(visible=False)
  6283. for plot_obj in objs:
  6284. plot_obj.shapes.redraw()
  6285. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6286. def toggle_plots(self, objects):
  6287. """
  6288. Toggle plots visibility
  6289. :param objects: list of Objects for which to be toggled the visibility
  6290. :return: None
  6291. """
  6292. # if no objects selected then do nothing
  6293. if not self.collection.get_selected():
  6294. return
  6295. log.debug("Toggling plots ...")
  6296. self.inform.emit(_("Working ..."))
  6297. for obj in objects:
  6298. if obj.options['plot'] is False:
  6299. obj.options['plot'] = True
  6300. else:
  6301. obj.options['plot'] = False
  6302. self.app_obj.plots_updated.emit()
  6303. def clear_plots(self):
  6304. """
  6305. Clear the plots
  6306. :return: None
  6307. """
  6308. objects = self.collection.get_list()
  6309. for obj in objects:
  6310. obj.clear(obj == objects[-1])
  6311. # Clear pool to free memory
  6312. self.clear_pool()
  6313. def on_set_color_action_triggered(self):
  6314. """
  6315. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6316. :return:
  6317. """
  6318. new_color = self.defaults['gerber_plot_fill']
  6319. clicked_action = self.sender()
  6320. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6321. act_name = clicked_action.text()
  6322. sel_obj_list = self.collection.get_selected()
  6323. if not sel_obj_list:
  6324. return
  6325. # a default value, I just chose this one
  6326. alpha_level = 'BF'
  6327. for sel_obj in sel_obj_list:
  6328. if sel_obj.kind == 'excellon':
  6329. alpha_level = str(hex(
  6330. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6331. elif sel_obj.kind == 'gerber':
  6332. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6333. elif sel_obj.kind == 'geometry':
  6334. alpha_level = 'FF'
  6335. else:
  6336. log.debug(
  6337. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6338. continue
  6339. sel_obj.alpha_level = alpha_level
  6340. if act_name == _('Red'):
  6341. new_color = '#FF0000' + alpha_level
  6342. if act_name == _('Blue'):
  6343. new_color = '#0000FF' + alpha_level
  6344. if act_name == _('Yellow'):
  6345. new_color = '#FFDF00' + alpha_level
  6346. if act_name == _('Green'):
  6347. new_color = '#00FF00' + alpha_level
  6348. if act_name == _('Purple'):
  6349. new_color = '#FF00FF' + alpha_level
  6350. if act_name == _('Brown'):
  6351. new_color = '#A52A2A' + alpha_level
  6352. if act_name == _('White'):
  6353. new_color = '#FFFFFF' + alpha_level
  6354. if act_name == _('Black'):
  6355. new_color = '#000000' + alpha_level
  6356. if act_name == _('Custom'):
  6357. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6358. c_dialog = QtWidgets.QColorDialog()
  6359. plot_fill_color = c_dialog.getColor(initial=new_color)
  6360. if plot_fill_color.isValid() is False:
  6361. return
  6362. new_color = str(plot_fill_color.name()) + alpha_level
  6363. if act_name == _("Default"):
  6364. for sel_obj in sel_obj_list:
  6365. if sel_obj.kind == 'excellon':
  6366. new_color = self.defaults['excellon_plot_fill']
  6367. new_line_color = self.defaults['excellon_plot_line']
  6368. elif sel_obj.kind == 'gerber':
  6369. new_color = self.defaults['gerber_plot_fill']
  6370. new_line_color = self.defaults['gerber_plot_line']
  6371. elif sel_obj.kind == 'geometry':
  6372. new_color = self.defaults['geometry_plot_line']
  6373. new_line_color = self.defaults['geometry_plot_line']
  6374. else:
  6375. log.debug(
  6376. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6377. continue
  6378. sel_obj.fill_color = new_color
  6379. sel_obj.outline_color = new_line_color
  6380. sel_obj.shapes.redraw(
  6381. update_colors=(new_color, new_line_color)
  6382. )
  6383. return
  6384. if act_name == _("Opacity"):
  6385. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  6386. # self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  6387. alpha_dialog = FCInputDialogSlider(
  6388. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6389. alpha_level, ok_button = alpha_dialog.get_results()
  6390. if ok_button:
  6391. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6392. for sel_obj in sel_obj_list:
  6393. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6394. sel_obj.shapes.redraw(
  6395. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6396. )
  6397. return
  6398. new_line_color = color_variant(new_color[:7], 0.7)
  6399. if act_name == _("White"):
  6400. new_line_color = color_variant("#dedede", 0.7)
  6401. for sel_obj in sel_obj_list:
  6402. sel_obj.fill_color = new_color
  6403. sel_obj.outline_color = new_line_color
  6404. sel_obj.shapes.redraw(
  6405. update_colors=(new_color, new_line_color)
  6406. )
  6407. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6408. group = self.collection.group_items["gerber"]
  6409. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6410. new_c = (new_line_color, new_color)
  6411. for sel_obj in sel_obj_list:
  6412. if sel_obj.kind == 'gerber':
  6413. item = sel_obj.item
  6414. item_index = self.collection.index(item.row(), 0, group_index)
  6415. idx = item_index.row()
  6416. self.defaults["gerber_color_list"][idx] = new_c
  6417. def generate_cnc_job(self, objects):
  6418. """
  6419. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6420. :param objects: Selected objects in the Project Tab
  6421. :return:
  6422. """
  6423. self.defaults.report_usage("generate_cnc_job()")
  6424. # for obj in objects:
  6425. # obj.generatecncjob()
  6426. for obj in objects:
  6427. obj.on_generatecnc_button_click()
  6428. def start_delayed_quit(self, delay, filename, should_quit=None):
  6429. """
  6430. :param delay: period of checking if project file size is more than zero; in seconds
  6431. :param filename: the name of the project file to be checked periodically for size more than zero
  6432. :param should_quit: if the task finished will be followed by an app quit; boolean
  6433. :return:
  6434. """
  6435. to_quit = should_quit
  6436. self.save_timer = QtCore.QTimer()
  6437. self.save_timer.setInterval(delay)
  6438. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6439. self.save_timer.start()
  6440. def check_project_file_size(self, filename, should_quit=None):
  6441. """
  6442. :param filename: the name of the project file to be checked periodically for size more than zero
  6443. :param should_quit: will quit the app if True; boolean
  6444. :return:
  6445. """
  6446. try:
  6447. if os.stat(filename).st_size > 0:
  6448. self.save_in_progress = False
  6449. self.save_timer.stop()
  6450. if should_quit:
  6451. self.app_quit.emit()
  6452. except Exception:
  6453. traceback.print_exc()
  6454. def save_project_auto(self):
  6455. """
  6456. Called periodically to save the project.
  6457. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  6458. # progress.
  6459. :return:
  6460. """
  6461. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6462. self.on_file_saveproject()
  6463. def save_project_auto_update(self):
  6464. """
  6465. Update the auto save time interval value.
  6466. :return:
  6467. """
  6468. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6469. try:
  6470. if self.autosave_timer.isActive():
  6471. self.autosave_timer.stop()
  6472. except Exception:
  6473. pass
  6474. if self.defaults['global_autosave'] is True:
  6475. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6476. self.autosave_timer.start()
  6477. def on_options_app2project(self):
  6478. """
  6479. Callback for Options->Transfer Options->App=>Project. Copies options
  6480. from application defaults to project defaults.
  6481. :return: None
  6482. """
  6483. self.defaults.report_usage("on_options_app2project")
  6484. self.preferencesUiManager.defaults_read_form()
  6485. self.options.update(self.defaults)
  6486. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6487. """
  6488. Shows a message on the FlatCAM Shell
  6489. :param msg: Message to display.
  6490. :param show: Opens the shell.
  6491. :param error: Shows the message as an error.
  6492. :param warning: Shows the message as an warning.
  6493. :param success: Shows the message as an success.
  6494. :param selected: Indicate that something was selected on canvas
  6495. :return: None
  6496. """
  6497. end = '\n' if new_line is True else ''
  6498. if show:
  6499. self.ui.shell_dock.show()
  6500. try:
  6501. if error:
  6502. self.shell.append_error(msg + end)
  6503. elif warning:
  6504. self.shell.append_warning(msg + end)
  6505. elif success:
  6506. self.shell.append_success(msg + end)
  6507. elif selected:
  6508. self.shell.append_selected(msg + end)
  6509. else:
  6510. self.shell.append_output(msg + end)
  6511. except AttributeError:
  6512. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6513. def dec_format(self, val, dec=None):
  6514. """
  6515. Returns a formatted float value with a certain number of decimals
  6516. """
  6517. dec_nr = dec if dec is not None else self.decimals
  6518. return float('%.*f' % (dec_nr, val))
  6519. class ArgsThread(QtCore.QObject):
  6520. open_signal = pyqtSignal(list)
  6521. start = pyqtSignal()
  6522. stop = pyqtSignal()
  6523. if sys.platform == 'win32':
  6524. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6525. else:
  6526. address = ('/tmp/testipc', 'AF_UNIX')
  6527. def __init__(self):
  6528. super().__init__()
  6529. self.listener = None
  6530. self.thread_exit = False
  6531. self.start.connect(self.run)
  6532. self.stop.connect(self.close_listener)
  6533. def my_loop(self, address):
  6534. try:
  6535. self.listener = Listener(*address)
  6536. while self.thread_exit is False:
  6537. conn = self.listener.accept()
  6538. self.serve(conn)
  6539. except socket.error:
  6540. try:
  6541. conn = Client(*address)
  6542. conn.send(sys.argv)
  6543. conn.send('close')
  6544. # close the current instance only if there are args
  6545. if len(sys.argv) > 1:
  6546. try:
  6547. self.listener.close()
  6548. except Exception:
  6549. pass
  6550. sys.exit()
  6551. except ConnectionRefusedError:
  6552. if sys.platform == 'win32':
  6553. pass
  6554. else:
  6555. os.system('rm /tmp/testipc')
  6556. self.listener = Listener(*address)
  6557. while True:
  6558. conn = self.listener.accept()
  6559. self.serve(conn)
  6560. def serve(self, conn):
  6561. while self.thread_exit is False:
  6562. msg = conn.recv()
  6563. if msg == 'close':
  6564. break
  6565. self.open_signal.emit(msg)
  6566. conn.close()
  6567. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6568. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6569. @pyqtSlot()
  6570. def run(self):
  6571. self.my_loop(self.address)
  6572. @pyqtSlot()
  6573. def close_listener(self):
  6574. self.thread_exit = True
  6575. self.listener.close()
  6576. class MenuFileHandlers(QtCore.QObject):
  6577. def __init__(self, app):
  6578. super().__init__()
  6579. self.app = app
  6580. self.inform = self.app.inform
  6581. self.splash = self.app.splash
  6582. self.worker_task = self.app.worker_task
  6583. self.defaults = self.app.defaults
  6584. self.pagesize = {}
  6585. def on_fileopengerber(self, signal, name=None):
  6586. """
  6587. File menu callback for opening a Gerber.
  6588. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6589. :param name:
  6590. :return: None
  6591. """
  6592. self.app.log.debug("on_fileopengerber()")
  6593. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6594. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6595. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6596. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6597. "*.outline);;" \
  6598. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6599. "*.mil);;" \
  6600. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6601. "Allegro Files (*.art);;" \
  6602. "Mentor Files (*.pho *.gdo);;" \
  6603. "All Files (*.*)"
  6604. if name is None:
  6605. try:
  6606. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6607. directory=self.app.get_last_folder(),
  6608. filter=_filter_,
  6609. initialFilter=self.app.last_op_gerber_filter)
  6610. except TypeError:
  6611. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6612. filenames = [str(filename) for filename in filenames]
  6613. self.app.last_op_gerber_filter = _f
  6614. else:
  6615. filenames = [name]
  6616. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6617. "Canvas initialization finished in"),
  6618. '%.2f' % self.app.used_time,
  6619. _("Opening Gerber file.")),
  6620. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6621. color=QtGui.QColor("gray"))
  6622. if len(filenames) == 0:
  6623. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6624. else:
  6625. for filename in filenames:
  6626. if filename != '':
  6627. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6628. def on_fileopenexcellon(self, signal, name=None):
  6629. """
  6630. File menu callback for opening an Excellon file.
  6631. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6632. :param name:
  6633. :return: None
  6634. """
  6635. self.app.log.debug("on_fileopenexcellon()")
  6636. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6637. "All Files (*.*)"
  6638. if name is None:
  6639. try:
  6640. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6641. directory=self.app.get_last_folder(),
  6642. filter=_filter_,
  6643. initialFilter=self.app.last_op_excellon_filter)
  6644. except TypeError:
  6645. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6646. filenames = [str(filename) for filename in filenames]
  6647. self.app.last_op_excellon_filter = _f
  6648. else:
  6649. filenames = [str(name)]
  6650. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6651. "Canvas initialization finished in"),
  6652. '%.2f' % self.app.used_time,
  6653. _("Opening Excellon file.")),
  6654. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6655. color=QtGui.QColor("gray"))
  6656. if len(filenames) == 0:
  6657. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6658. else:
  6659. for filename in filenames:
  6660. if filename != '':
  6661. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6662. def on_fileopengcode(self, signal, name=None):
  6663. """
  6664. File menu call back for opening gcode.
  6665. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6666. :param name:
  6667. :return:
  6668. """
  6669. self.app.log.debug("on_fileopengcode()")
  6670. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6671. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6672. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6673. "All Files (*.*)"
  6674. if name is None:
  6675. try:
  6676. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6677. directory=self.app.get_last_folder(),
  6678. filter=_filter_,
  6679. initialFilter=self.app.last_op_gcode_filter)
  6680. except TypeError:
  6681. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6682. filenames = [str(filename) for filename in filenames]
  6683. self.app.last_op_gcode_filter = _f
  6684. else:
  6685. filenames = [name]
  6686. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6687. "Canvas initialization finished in"),
  6688. '%.2f' % self.app.used_time,
  6689. _("Opening G-Code file.")),
  6690. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6691. color=QtGui.QColor("gray"))
  6692. if len(filenames) == 0:
  6693. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6694. else:
  6695. for filename in filenames:
  6696. if filename != '':
  6697. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6698. def on_file_openproject(self, signal):
  6699. """
  6700. File menu callback for opening a project.
  6701. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6702. :return: None
  6703. """
  6704. self.app.log.debug("on_file_openproject()")
  6705. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6706. try:
  6707. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6708. directory=self.app.get_last_folder(), filter=_filter_)
  6709. except TypeError:
  6710. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6711. filename = str(filename)
  6712. if filename == "":
  6713. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6714. else:
  6715. # self.worker_task.emit({'fcn': self.open_project,
  6716. # 'params': [filename]})
  6717. # The above was failing because open_project() is not
  6718. # thread safe. The new_project()
  6719. self.open_project(filename)
  6720. def on_fileopenhpgl2(self, signal, name=None):
  6721. """
  6722. File menu callback for opening a HPGL2.
  6723. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6724. :param name:
  6725. :return: None
  6726. """
  6727. self.app.log.debug("on_fileopenhpgl2()")
  6728. _filter_ = "HPGL2 Files (*.plt);;" \
  6729. "All Files (*.*)"
  6730. if name is None:
  6731. try:
  6732. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6733. directory=self.app.get_last_folder(),
  6734. filter=_filter_)
  6735. except TypeError:
  6736. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6737. filenames = [str(filename) for filename in filenames]
  6738. else:
  6739. filenames = [name]
  6740. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6741. "Canvas initialization finished in"),
  6742. '%.2f' % self.app.used_time,
  6743. _("Opening HPGL2 file.")),
  6744. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6745. color=QtGui.QColor("gray"))
  6746. if len(filenames) == 0:
  6747. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6748. else:
  6749. for filename in filenames:
  6750. if filename != '':
  6751. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6752. def on_file_openconfig(self, signal):
  6753. """
  6754. File menu callback for opening a config file.
  6755. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6756. :return: None
  6757. """
  6758. self.app.log.debug("on_file_openconfig()")
  6759. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6760. try:
  6761. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6762. directory=self.app.data_path, filter=_filter_)
  6763. except TypeError:
  6764. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6765. filter=_filter_)
  6766. if filename == "":
  6767. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6768. else:
  6769. self.open_config_file(filename)
  6770. def on_file_exportsvg(self):
  6771. """
  6772. Callback for menu item File->Export SVG.
  6773. :return: None
  6774. """
  6775. self.app.log.debug("on_file_exportsvg()")
  6776. obj = self.app.collection.get_active()
  6777. if obj is None:
  6778. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6779. msg = _("Please Select a Geometry object to export")
  6780. msgbox = QtWidgets.QMessageBox()
  6781. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6782. msgbox.setInformativeText(msg)
  6783. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6784. msgbox.setDefaultButton(bt_ok)
  6785. msgbox.exec_()
  6786. return
  6787. # Check for more compatible types and add as required
  6788. if (not isinstance(obj, GeometryObject)
  6789. and not isinstance(obj, GerberObject)
  6790. and not isinstance(obj, CNCJobObject)
  6791. and not isinstance(obj, ExcellonObject)):
  6792. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6793. msgbox = QtWidgets.QMessageBox()
  6794. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6795. msgbox.setInformativeText(msg)
  6796. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6797. msgbox.setDefaultButton(bt_ok)
  6798. msgbox.exec_()
  6799. return
  6800. name = obj.options["name"]
  6801. _filter = "SVG File (*.svg);;All Files (*.*)"
  6802. try:
  6803. filename, _f = FCFileSaveDialog.get_saved_filename(
  6804. caption=_("Export SVG"),
  6805. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6806. ext_filter=_filter)
  6807. except TypeError:
  6808. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  6809. filename = str(filename)
  6810. if filename == "":
  6811. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6812. return
  6813. else:
  6814. self.export_svg(name, filename)
  6815. if self.defaults["global_open_style"] is False:
  6816. self.app.file_opened.emit("SVG", filename)
  6817. self.app.file_saved.emit("SVG", filename)
  6818. def on_file_exportpng(self):
  6819. self.app.log.debug("on_file_exportpng()")
  6820. date = str(datetime.today()).rpartition('.')[0]
  6821. date = ''.join(c for c in date if c not in ':-')
  6822. date = self.app.date.replace(' ', '_')
  6823. data = None
  6824. if self.app.is_legacy is False:
  6825. image = _screenshot(alpha=False)
  6826. data = np.asarray(image)
  6827. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6828. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6829. return
  6830. filter_ = "PNG File (*.png);;All Files (*.*)"
  6831. try:
  6832. filename, _f = FCFileSaveDialog.get_saved_filename(
  6833. caption=_("Export PNG Image"),
  6834. directory=self.app.get_last_save_folder() + '/png_' + date,
  6835. ext_filter=filter_)
  6836. except TypeError:
  6837. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6838. filename = str(filename)
  6839. if filename == "":
  6840. self.inform.emit(_("Cancelled."))
  6841. return
  6842. else:
  6843. if self.app.is_legacy is False:
  6844. write_png(filename, data)
  6845. else:
  6846. self.app.plotcanvas.figure.savefig(filename)
  6847. if self.defaults["global_open_style"] is False:
  6848. self.app.file_opened.emit("png", filename)
  6849. self.app.file_saved.emit("png", filename)
  6850. def on_file_savegerber(self):
  6851. """
  6852. Callback for menu item in Project context menu.
  6853. :return: None
  6854. """
  6855. self.app.log.debug("on_file_savegerber()")
  6856. obj = self.app.collection.get_active()
  6857. if obj is None:
  6858. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6859. return
  6860. # Check for more compatible types and add as required
  6861. if not isinstance(obj, GerberObject):
  6862. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6863. return
  6864. name = self.app.collection.get_active().options["name"]
  6865. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6866. try:
  6867. filename, _f = FCFileSaveDialog.get_saved_filename(
  6868. caption="Save Gerber source file",
  6869. directory=self.app.get_last_save_folder() + '/' + name,
  6870. ext_filter=_filter)
  6871. except TypeError:
  6872. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6873. filename = str(filename)
  6874. if filename == "":
  6875. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6876. return
  6877. else:
  6878. self.save_source_file(name, filename)
  6879. if self.defaults["global_open_style"] is False:
  6880. self.app.file_opened.emit("Gerber", filename)
  6881. self.app.file_saved.emit("Gerber", filename)
  6882. def on_file_savescript(self):
  6883. """
  6884. Callback for menu item in Project context menu.
  6885. :return: None
  6886. """
  6887. self.app.log.debug("on_file_savescript()")
  6888. obj = self.app.collection.get_active()
  6889. if obj is None:
  6890. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6891. return
  6892. # Check for more compatible types and add as required
  6893. if not isinstance(obj, ScriptObject):
  6894. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6895. return
  6896. name = self.app.collection.get_active().options["name"]
  6897. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6898. try:
  6899. filename, _f = FCFileSaveDialog.get_saved_filename(
  6900. caption="Save Script source file",
  6901. directory=self.app.get_last_save_folder() + '/' + name,
  6902. ext_filter=_filter)
  6903. except TypeError:
  6904. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6905. filename = str(filename)
  6906. if filename == "":
  6907. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6908. return
  6909. else:
  6910. self.save_source_file(name, filename)
  6911. if self.defaults["global_open_style"] is False:
  6912. self.app.file_opened.emit("Script", filename)
  6913. self.app.file_saved.emit("Script", filename)
  6914. def on_file_savedocument(self):
  6915. """
  6916. Callback for menu item in Project context menu.
  6917. :return: None
  6918. """
  6919. self.app.log.debug("on_file_savedocument()")
  6920. obj = self.app.collection.get_active()
  6921. if obj is None:
  6922. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6923. return
  6924. # Check for more compatible types and add as required
  6925. if not isinstance(obj, ScriptObject):
  6926. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6927. return
  6928. name = self.app.collection.get_active().options["name"]
  6929. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6930. try:
  6931. filename, _f = FCFileSaveDialog.get_saved_filename(
  6932. caption="Save Document source file",
  6933. directory=self.app.get_last_save_folder() + '/' + name,
  6934. ext_filter=_filter)
  6935. except TypeError:
  6936. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6937. ext_filter=_filter)
  6938. filename = str(filename)
  6939. if filename == "":
  6940. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6941. return
  6942. else:
  6943. self.save_source_file(name, filename)
  6944. if self.defaults["global_open_style"] is False:
  6945. self.app.file_opened.emit("Document", filename)
  6946. self.app.file_saved.emit("Document", filename)
  6947. def on_file_saveexcellon(self):
  6948. """
  6949. Callback for menu item in project context menu.
  6950. :return: None
  6951. """
  6952. self.app.log.debug("on_file_saveexcellon()")
  6953. obj = self.app.collection.get_active()
  6954. if obj is None:
  6955. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6956. return
  6957. # Check for more compatible types and add as required
  6958. if not isinstance(obj, ExcellonObject):
  6959. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6960. return
  6961. name = self.app.collection.get_active().options["name"]
  6962. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6963. try:
  6964. filename, _f = FCFileSaveDialog.get_saved_filename(
  6965. caption=_("Save Excellon source file"),
  6966. directory=self.app.get_last_save_folder() + '/' + name,
  6967. ext_filter=_filter)
  6968. except TypeError:
  6969. filename, _f = FCFileSaveDialog.get_saved_filename(
  6970. caption=_("Save Excellon source file"), ext_filter=_filter)
  6971. filename = str(filename)
  6972. if filename == "":
  6973. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6974. return
  6975. else:
  6976. self.save_source_file(name, filename)
  6977. if self.defaults["global_open_style"] is False:
  6978. self.app.file_opened.emit("Excellon", filename)
  6979. self.app.file_saved.emit("Excellon", filename)
  6980. def on_file_exportexcellon(self):
  6981. """
  6982. Callback for menu item File->Export->Excellon.
  6983. :return: None
  6984. """
  6985. self.app.log.debug("on_file_exportexcellon()")
  6986. obj = self.app.collection.get_active()
  6987. if obj is None:
  6988. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6989. return
  6990. # Check for more compatible types and add as required
  6991. if not isinstance(obj, ExcellonObject):
  6992. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6993. return
  6994. name = self.app.collection.get_active().options["name"]
  6995. _filter = self.defaults["excellon_save_filters"]
  6996. try:
  6997. filename, _f = FCFileSaveDialog.get_saved_filename(
  6998. caption=_("Export Excellon"),
  6999. directory=self.app.get_last_save_folder() + '/' + name,
  7000. ext_filter=_filter)
  7001. except TypeError:
  7002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  7003. filename = str(filename)
  7004. if filename == "":
  7005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7006. return
  7007. else:
  7008. used_extension = filename.rpartition('.')[2]
  7009. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7010. self.export_excellon(name, filename)
  7011. if self.defaults["global_open_style"] is False:
  7012. self.app.file_opened.emit("Excellon", filename)
  7013. self.app.file_saved.emit("Excellon", filename)
  7014. def on_file_exportgerber(self):
  7015. """
  7016. Callback for menu item File->Export->Gerber.
  7017. :return: None
  7018. """
  7019. App.log.debug("on_file_exportgerber()")
  7020. obj = self.app.collection.get_active()
  7021. if obj is None:
  7022. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7023. return
  7024. # Check for more compatible types and add as required
  7025. if not isinstance(obj, GerberObject):
  7026. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7027. return
  7028. name = self.app.collection.get_active().options["name"]
  7029. _filter_ = self.defaults['gerber_save_filters']
  7030. try:
  7031. filename, _f = FCFileSaveDialog.get_saved_filename(
  7032. caption=_("Export Gerber"),
  7033. directory=self.app.get_last_save_folder() + '/' + name,
  7034. ext_filter=_filter_)
  7035. except TypeError:
  7036. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  7037. filename = str(filename)
  7038. if filename == "":
  7039. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7040. return
  7041. else:
  7042. used_extension = filename.rpartition('.')[2]
  7043. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7044. self.export_gerber(name, filename)
  7045. if self.defaults["global_open_style"] is False:
  7046. self.app.file_opened.emit("Gerber", filename)
  7047. self.app.file_saved.emit("Gerber", filename)
  7048. def on_file_exportdxf(self):
  7049. """
  7050. Callback for menu item File->Export DXF.
  7051. :return: None
  7052. """
  7053. App.log.debug("on_file_exportdxf()")
  7054. obj = self.app.collection.get_active()
  7055. if obj is None:
  7056. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7057. msg = _("Please Select a Geometry object to export")
  7058. msgbox = QtWidgets.QMessageBox()
  7059. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7060. msgbox.setInformativeText(msg)
  7061. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7062. msgbox.setDefaultButton(bt_ok)
  7063. msgbox.exec_()
  7064. return
  7065. # Check for more compatible types and add as required
  7066. if not isinstance(obj, GeometryObject):
  7067. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7068. msgbox = QtWidgets.QMessageBox()
  7069. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7070. msgbox.setInformativeText(msg)
  7071. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7072. msgbox.setDefaultButton(bt_ok)
  7073. msgbox.exec_()
  7074. return
  7075. name = self.app.collection.get_active().options["name"]
  7076. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7077. try:
  7078. filename, _f = FCFileSaveDialog.get_saved_filename(
  7079. caption=_("Export DXF"),
  7080. directory=self.app.get_last_save_folder() + '/' + name,
  7081. ext_filter=_filter_)
  7082. except TypeError:
  7083. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  7084. filename = str(filename)
  7085. if filename == "":
  7086. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7087. return
  7088. else:
  7089. self.export_dxf(name, filename)
  7090. if self.defaults["global_open_style"] is False:
  7091. self.app.file_opened.emit("DXF", filename)
  7092. self.app.file_saved.emit("DXF", filename)
  7093. def on_file_importsvg(self, type_of_obj):
  7094. """
  7095. Callback for menu item File->Import SVG.
  7096. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7097. :type type_of_obj: str
  7098. :return: None
  7099. """
  7100. self.app.log.debug("on_file_importsvg()")
  7101. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7102. try:
  7103. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7104. directory=self.app.get_last_folder(),
  7105. filter=_filter_)
  7106. except TypeError:
  7107. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7108. filter=_filter_)
  7109. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7110. type_of_obj = "geometry"
  7111. filenames = [str(filename) for filename in filenames]
  7112. if len(filenames) == 0:
  7113. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7114. else:
  7115. for filename in filenames:
  7116. if filename != '':
  7117. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7118. def on_file_importdxf(self, type_of_obj):
  7119. """
  7120. Callback for menu item File->Import DXF.
  7121. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7122. :type type_of_obj: str
  7123. :return: None
  7124. """
  7125. self.app.log.debug("on_file_importdxf()")
  7126. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7127. try:
  7128. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7129. directory=self.app.get_last_folder(),
  7130. filter=_filter_)
  7131. except TypeError:
  7132. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7133. filter=_filter_)
  7134. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7135. type_of_obj = "geometry"
  7136. filenames = [str(filename) for filename in filenames]
  7137. if len(filenames) == 0:
  7138. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7139. else:
  7140. for filename in filenames:
  7141. if filename != '':
  7142. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7143. def on_file_new_click(self):
  7144. """
  7145. Callback for menu item File -> New.
  7146. Executed on clicking the Menu -> File -> New Project
  7147. :return:
  7148. """
  7149. if self.app.collection.get_list() and self.app.should_we_save:
  7150. msgbox = QtWidgets.QMessageBox()
  7151. # msgbox.setText("<B>Save changes ...</B>")
  7152. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7153. "Creating a New project will delete them.\n"
  7154. "Do you want to Save the project?"))
  7155. msgbox.setWindowTitle(_("Save changes"))
  7156. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7157. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7158. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7159. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7160. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7161. msgbox.setDefaultButton(bt_yes)
  7162. msgbox.exec_()
  7163. response = msgbox.clickedButton()
  7164. if response == bt_yes:
  7165. self.on_file_saveprojectas()
  7166. elif response == bt_cancel:
  7167. return
  7168. elif response == bt_no:
  7169. self.on_file_new()
  7170. else:
  7171. self.on_file_new()
  7172. self.inform.emit('[success] %s...' % _("New Project created"))
  7173. def on_file_new(self, cli=None):
  7174. """
  7175. Returns the application to its startup state. This method is thread-safe.
  7176. :param cli: Boolean. If True this method was run from command line
  7177. :return: None
  7178. """
  7179. self.defaults.report_usage("on_file_new")
  7180. # Remove everything from memory
  7181. self.app.log.debug("on_file_new()")
  7182. # close any editor that might be open
  7183. if self.app.call_source != 'app':
  7184. self.app.editor2object(cleanup=True)
  7185. # ## EDITOR section
  7186. self.app.geo_editor = AppGeoEditor(self.app)
  7187. self.app.exc_editor = AppExcEditor(self.app)
  7188. self.app.grb_editor = AppGerberEditor(self.app)
  7189. # Clear pool
  7190. self.app.clear_pool()
  7191. for obj in self.app.collection.get_list():
  7192. # delete shapes left drawn from mark shape_collections, if any
  7193. if isinstance(obj, GerberObject):
  7194. try:
  7195. obj.mark_shapes_storage.clear()
  7196. obj.mark_shapes.clear(update=True)
  7197. obj.mark_shapes.enabled = False
  7198. except AttributeError:
  7199. pass
  7200. # also delete annotation shapes, if any
  7201. elif isinstance(obj, CNCJobObject):
  7202. try:
  7203. obj.text_col.enabled = False
  7204. del obj.text_col
  7205. obj.annotation.clear(update=True)
  7206. del obj.annotation
  7207. except AttributeError:
  7208. pass
  7209. # delete the exclusion areas
  7210. self.app.exc_areas.clear_shapes()
  7211. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7212. self.app.shell.init_tcl()
  7213. # delete any selection shape on canvas
  7214. self.app.delete_selection_shape()
  7215. # delete all FlatCAM objects
  7216. self.app.collection.delete_all()
  7217. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7218. self.app.setup_default_properties_tab()
  7219. # Clear project filename
  7220. self.app.project_filename = None
  7221. # Load the application defaults
  7222. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7223. # Re-fresh project options
  7224. self.app.on_options_app2project()
  7225. # Init FlatCAMTools
  7226. self.app.init_tools()
  7227. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7228. if cli is None:
  7229. # we need to go in reverse because once we remove a tab then the index changes
  7230. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7231. # and so on. Therefore the deletion should be done in reverse
  7232. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7233. for index in range(wdg_count, -1, -1):
  7234. try:
  7235. self.app.ui.plot_tab_area.closeTab(index)
  7236. except Exception as e:
  7237. log.debug("App.on_file_new() --> %s" % str(e))
  7238. # # And then add again the Plot Area
  7239. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7240. self.app.ui.plot_tab_area.protectTab(0)
  7241. # take the focus of the Notebook on Project Tab.
  7242. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7243. self.app.set_ui_title(name=_("New Project - Not saved"))
  7244. def on_filenewscript(self, silent=False):
  7245. """
  7246. Will create a new script file and open it in the Code Editor
  7247. :param silent: if True will not display status messages
  7248. :return: None
  7249. """
  7250. if silent is False:
  7251. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7252. # hide coordinates toolbars in the infobar while in DB
  7253. self.app.ui.coords_toolbar.hide()
  7254. self.app.ui.delta_coords_toolbar.hide()
  7255. self.app.app_obj.new_script_object()
  7256. def on_fileopenscript(self, name=None, silent=False):
  7257. """
  7258. Will open a Tcl script file into the Code Editor
  7259. :param silent: if True will not display status messages
  7260. :param name: name of a Tcl script file to open
  7261. :return: None
  7262. """
  7263. self.app.log.debug("on_fileopenscript()")
  7264. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7265. "All Files (*.*)"
  7266. if name:
  7267. filenames = [name]
  7268. else:
  7269. try:
  7270. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7271. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7272. except TypeError:
  7273. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7274. if len(filenames) == 0:
  7275. if silent is False:
  7276. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7277. else:
  7278. for filename in filenames:
  7279. if filename != '':
  7280. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7281. def on_fileopenscript_example(self, name=None, silent=False):
  7282. """
  7283. Will open a Tcl script file into the Code Editor
  7284. :param silent: if True will not display status messages
  7285. :param name: name of a Tcl script file to open
  7286. :return:
  7287. """
  7288. self.app.log.debug("on_fileopenscript_example()")
  7289. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7290. "All Files (*.*)"
  7291. # test if the app was frozen and choose the path for the configuration file
  7292. if getattr(sys, "frozen", False) is True:
  7293. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7294. else:
  7295. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7296. if name:
  7297. filenames = [name]
  7298. else:
  7299. try:
  7300. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7301. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7302. except TypeError:
  7303. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7304. if len(filenames) == 0:
  7305. if silent is False:
  7306. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7307. else:
  7308. for filename in filenames:
  7309. if filename != '':
  7310. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7311. def on_filerunscript(self, name=None, silent=False):
  7312. """
  7313. File menu callback for loading and running a TCL script.
  7314. :param silent: if True will not display status messages
  7315. :param name: name of a Tcl script file to be run by FlatCAM
  7316. :return: None
  7317. """
  7318. self.app.log.debug("on_file_runscript()")
  7319. if name:
  7320. filename = name
  7321. if self.app.cmd_line_headless != 1:
  7322. self.splash.showMessage('%s: %ssec\n%s' %
  7323. (_("Canvas initialization started.\n"
  7324. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7325. _("Executing ScriptObject file.")
  7326. ),
  7327. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7328. color=QtGui.QColor("gray"))
  7329. else:
  7330. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7331. "All Files (*.*)"
  7332. try:
  7333. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7334. directory=self.app.get_last_folder(),
  7335. filter=_filter_)
  7336. except TypeError:
  7337. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7338. # The Qt methods above will return a QString which can cause problems later.
  7339. # So far json.dump() will fail to serialize it.
  7340. filename = str(filename)
  7341. if filename == "":
  7342. if silent is False:
  7343. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7344. else:
  7345. if self.app.cmd_line_headless != 1:
  7346. if self.app.ui.shell_dock.isHidden():
  7347. self.app.ui.shell_dock.show()
  7348. try:
  7349. with open(filename, "r") as tcl_script:
  7350. cmd_line_shellfile_content = tcl_script.read()
  7351. if self.app.cmd_line_headless != 1:
  7352. self.app.shell.exec_command(cmd_line_shellfile_content)
  7353. else:
  7354. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7355. if silent is False:
  7356. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7357. except Exception as e:
  7358. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7359. sys.exit(2)
  7360. def on_file_saveproject(self, silent=False):
  7361. """
  7362. Callback for menu item File->Save Project. Saves the project to
  7363. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7364. if set to None. The project is saved by calling ``self.save_project()``.
  7365. :param silent: if True will not display status messages
  7366. :return: None
  7367. """
  7368. if self.app.project_filename is None:
  7369. self.on_file_saveprojectas()
  7370. else:
  7371. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7372. if self.defaults["global_open_style"] is False:
  7373. self.app.file_opened.emit("project", self.project_filename)
  7374. self.app.file_saved.emit("project", self.project_filename)
  7375. self.app.set_ui_title(name=self.app.project_filename)
  7376. self.app.should_we_save = False
  7377. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7378. """
  7379. Callback for menu item File->Save Project As... Opens a file
  7380. chooser and saves the project to the given file via
  7381. ``self.save_project()``.
  7382. :param make_copy if to be create a copy of the project; boolean
  7383. :param use_thread: if to be run in a separate thread; boolean
  7384. :param quit_action: if to be followed by quiting the application; boolean
  7385. :return: None
  7386. """
  7387. date = str(datetime.today()).rpartition('.')[0]
  7388. date = ''.join(c for c in date if c not in ':-')
  7389. date = self.date.replace(' ', '_')
  7390. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7391. try:
  7392. filename, _f = FCFileSaveDialog.get_saved_filename(
  7393. caption=_("Save Project As ..."),
  7394. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7395. proj=_("Project")),
  7396. ext_filter=filter_
  7397. )
  7398. except TypeError:
  7399. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  7400. filename = str(filename)
  7401. if filename == '':
  7402. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7403. return
  7404. if use_thread is True:
  7405. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7406. else:
  7407. self.save_project(filename, quit_action)
  7408. # self.save_project(filename)
  7409. if self.defaults["global_open_style"] is False:
  7410. self.app.file_opened.emit("project", filename)
  7411. self.app.file_saved.emit("project", filename)
  7412. if not make_copy:
  7413. self.app.project_filename = filename
  7414. self.app.set_ui_title(name=self.app.project_filename)
  7415. self.app.should_we_save = False
  7416. def on_file_save_objects_pdf(self, use_thread=True):
  7417. date = str(datetime.today()).rpartition('.')[0]
  7418. date = ''.join(c for c in date if c not in ':-')
  7419. date = date.replace(' ', '_')
  7420. try:
  7421. obj_selection = self.app.collection.get_selected()
  7422. if len(obj_selection) == 1:
  7423. obj_name = str(obj_selection[0].options['name'])
  7424. else:
  7425. obj_name = _("FlatCAM objects print")
  7426. except AttributeError as err:
  7427. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7428. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7429. return
  7430. if not obj_selection:
  7431. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7432. return
  7433. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7434. try:
  7435. filename, _f = FCFileSaveDialog.get_saved_filename(
  7436. caption=_("Save Object as PDF ..."),
  7437. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7438. obj_name=obj_name,
  7439. date=date),
  7440. ext_filter=filter_
  7441. )
  7442. except TypeError:
  7443. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  7444. filename = str(filename)
  7445. if filename == '':
  7446. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7447. return
  7448. if use_thread is True:
  7449. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7450. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7451. else:
  7452. self.save_pdf(filename, obj_selection)
  7453. # self.save_project(filename)
  7454. if self.defaults["global_open_style"] is False:
  7455. self.app.file_opened.emit("pdf", filename)
  7456. self.app.file_saved.emit("pdf", filename)
  7457. def save_pdf(self, file_name, obj_selection):
  7458. p_size = self.defaults['global_workspaceT']
  7459. orientation = self.defaults['global_workspace_orientation']
  7460. color = 'black'
  7461. transparency_level = 1.0
  7462. self.pagesize.update(
  7463. {
  7464. 'Bounds': None,
  7465. 'A0': (841 * mm, 1189 * mm),
  7466. 'A1': (594 * mm, 841 * mm),
  7467. 'A2': (420 * mm, 594 * mm),
  7468. 'A3': (297 * mm, 420 * mm),
  7469. 'A4': (210 * mm, 297 * mm),
  7470. 'A5': (148 * mm, 210 * mm),
  7471. 'A6': (105 * mm, 148 * mm),
  7472. 'A7': (74 * mm, 105 * mm),
  7473. 'A8': (52 * mm, 74 * mm),
  7474. 'A9': (37 * mm, 52 * mm),
  7475. 'A10': (26 * mm, 37 * mm),
  7476. 'B0': (1000 * mm, 1414 * mm),
  7477. 'B1': (707 * mm, 1000 * mm),
  7478. 'B2': (500 * mm, 707 * mm),
  7479. 'B3': (353 * mm, 500 * mm),
  7480. 'B4': (250 * mm, 353 * mm),
  7481. 'B5': (176 * mm, 250 * mm),
  7482. 'B6': (125 * mm, 176 * mm),
  7483. 'B7': (88 * mm, 125 * mm),
  7484. 'B8': (62 * mm, 88 * mm),
  7485. 'B9': (44 * mm, 62 * mm),
  7486. 'B10': (31 * mm, 44 * mm),
  7487. 'C0': (917 * mm, 1297 * mm),
  7488. 'C1': (648 * mm, 917 * mm),
  7489. 'C2': (458 * mm, 648 * mm),
  7490. 'C3': (324 * mm, 458 * mm),
  7491. 'C4': (229 * mm, 324 * mm),
  7492. 'C5': (162 * mm, 229 * mm),
  7493. 'C6': (114 * mm, 162 * mm),
  7494. 'C7': (81 * mm, 114 * mm),
  7495. 'C8': (57 * mm, 81 * mm),
  7496. 'C9': (40 * mm, 57 * mm),
  7497. 'C10': (28 * mm, 40 * mm),
  7498. # American paper sizes
  7499. 'LETTER': (8.5 * inch, 11 * inch),
  7500. 'LEGAL': (8.5 * inch, 14 * inch),
  7501. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7502. # From https://en.wikipedia.org/wiki/Paper_size
  7503. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7504. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7505. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7506. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7507. 'LEDGER': (17 * inch, 11 * inch),
  7508. }
  7509. )
  7510. exported_svg = []
  7511. for obj in obj_selection:
  7512. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7513. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7514. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7515. color = obj.fill_color[:-2]
  7516. transparency_level = obj.fill_color[-2:]
  7517. elif obj.kind.lower() == 'geometry':
  7518. color = self.defaults["global_draw_color"]
  7519. # Change the attributes of the exported SVG
  7520. # We don't need stroke-width
  7521. # We set opacity to maximum
  7522. # We set the colour to WHITE
  7523. root = ET.fromstring(svg_obj)
  7524. for child in root:
  7525. child.set('fill', str(color))
  7526. child.set('opacity', str(transparency_level))
  7527. child.set('stroke', str(color))
  7528. exported_svg.append(ET.tostring(root))
  7529. xmin = Inf
  7530. ymin = Inf
  7531. xmax = -Inf
  7532. ymax = -Inf
  7533. for obj in obj_selection:
  7534. try:
  7535. gxmin, gymin, gxmax, gymax = obj.bounds()
  7536. xmin = min([xmin, gxmin])
  7537. ymin = min([ymin, gymin])
  7538. xmax = max([xmax, gxmax])
  7539. ymax = max([ymax, gymax])
  7540. except Exception as e:
  7541. self.app.log.warning(
  7542. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7543. # Determine bounding area for svg export
  7544. bounds = [xmin, ymin, xmax, ymax]
  7545. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7546. # This contain the measure units
  7547. uom = obj_selection[0].units.lower()
  7548. # Define a boundary around SVG of about 1.0mm (~39mils)
  7549. if uom in "mm":
  7550. boundary = 1.0
  7551. else:
  7552. boundary = 0.0393701
  7553. # Convert everything to strings for use in the xml doc
  7554. svgwidth = str(size[0] + (2 * boundary))
  7555. svgheight = str(size[1] + (2 * boundary))
  7556. minx = str(bounds[0] - boundary)
  7557. miny = str(bounds[1] + boundary + size[1])
  7558. # Add a SVG Header and footer to the svg output from shapely
  7559. # The transform flips the Y Axis so that everything renders
  7560. # properly within svg apps such as inkscape
  7561. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7562. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7563. svg_header += 'width="' + svgwidth + uom + '" '
  7564. svg_header += 'height="' + svgheight + uom + '" '
  7565. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7566. svg_header += '>'
  7567. svg_header += '<g transform="scale(1,-1)">'
  7568. svg_footer = '</g> </svg>'
  7569. svg_elem = str(svg_header)
  7570. for svg_item in exported_svg:
  7571. svg_elem += str(svg_item)
  7572. svg_elem += str(svg_footer)
  7573. # Parse the xml through a xml parser just to add line feeds
  7574. # and to make it look more pretty for the output
  7575. doc = parse_xml_string(svg_elem)
  7576. doc_final = doc.toprettyxml()
  7577. try:
  7578. if self.defaults['units'].upper() == 'IN':
  7579. unit = inch
  7580. else:
  7581. unit = mm
  7582. doc_final = StringIO(doc_final)
  7583. drawing = svg2rlg(doc_final)
  7584. if p_size == 'Bounds':
  7585. renderPDF.drawToFile(drawing, file_name)
  7586. else:
  7587. if orientation == 'p':
  7588. page_size = portrait(self.pagesize[p_size])
  7589. else:
  7590. page_size = landscape(self.pagesize[p_size])
  7591. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7592. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7593. renderPDF.draw(drawing, my_canvas, 0, 0)
  7594. my_canvas.save()
  7595. except Exception as e:
  7596. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7597. return 'fail'
  7598. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7599. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7600. """
  7601. Exports a Geometry Object to an SVG file.
  7602. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7603. :param filename: Path to the SVG file to save to.
  7604. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7605. :return:
  7606. """
  7607. if filename is None:
  7608. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7609. is not None else self.defaults["global_last_folder"]
  7610. self.app.log.debug("export_svg()")
  7611. try:
  7612. obj = self.app.collection.get_by_name(str(obj_name))
  7613. except Exception:
  7614. return 'fail'
  7615. with self.app.proc_container.new(_("Exporting SVG")) as proc:
  7616. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7617. # Determine bounding area for svg export
  7618. bounds = obj.bounds()
  7619. size = obj.size()
  7620. # Convert everything to strings for use in the xml doc
  7621. svgwidth = str(size[0])
  7622. svgheight = str(size[1])
  7623. minx = str(bounds[0])
  7624. miny = str(bounds[1] - size[1])
  7625. uom = obj.units.lower()
  7626. # Add a SVG Header and footer to the svg output from shapely
  7627. # The transform flips the Y Axis so that everything renders
  7628. # properly within svg apps such as inkscape
  7629. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7630. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7631. svg_header += 'width="' + svgwidth + uom + '" '
  7632. svg_header += 'height="' + svgheight + uom + '" '
  7633. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7634. svg_header += '<g transform="scale(1,-1)">'
  7635. svg_footer = '</g> </svg>'
  7636. svg_elem = svg_header + exported_svg + svg_footer
  7637. # Parse the xml through a xml parser just to add line feeds
  7638. # and to make it look more pretty for the output
  7639. svgcode = parse_xml_string(svg_elem)
  7640. svgcode = svgcode.toprettyxml()
  7641. try:
  7642. with open(filename, 'w') as fp:
  7643. fp.write(svgcode)
  7644. except PermissionError:
  7645. self.inform.emit('[WARNING] %s' %
  7646. _("Permission denied, saving not possible.\n"
  7647. "Most likely another app is holding the file open and not accessible."))
  7648. return 'fail'
  7649. if self.defaults["global_open_style"] is False:
  7650. self.app.file_opened.emit("SVG", filename)
  7651. self.app.file_saved.emit("SVG", filename)
  7652. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7653. def on_import_preferences(self):
  7654. """
  7655. Loads the application default settings from a saved file into
  7656. ``self.defaults`` dictionary.
  7657. :return: None
  7658. """
  7659. self.app.log.debug("App.on_import_preferences()")
  7660. # Show file chooser
  7661. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7662. try:
  7663. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7664. directory=self.app.data_path,
  7665. filter=filter_)
  7666. except TypeError:
  7667. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7668. filter=filter_)
  7669. filename = str(filename)
  7670. if filename == "":
  7671. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7672. return
  7673. # Load in the defaults from the chosen file
  7674. self.defaults.load(filename=filename, inform=self.inform)
  7675. self.app.preferencesUiManager.on_preferences_edited()
  7676. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7677. def on_export_preferences(self):
  7678. """
  7679. Save the defaults dictionary to a file.
  7680. :return: None
  7681. """
  7682. self.app.log.debug("on_export_preferences()")
  7683. # defaults_file_content = None
  7684. # Show file chooser
  7685. date = str(datetime.today()).rpartition('.')[0]
  7686. date = ''.join(c for c in date if c not in ':-')
  7687. date = date.replace(' ', '_')
  7688. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7689. try:
  7690. filename, _f = FCFileSaveDialog.get_saved_filename(
  7691. caption=_("Export FlatCAM Preferences"),
  7692. directory=self.app.data_path + '/preferences_' + date,
  7693. ext_filter=filter__
  7694. )
  7695. except TypeError:
  7696. filename, _f = FCFileSaveDialog.get_saved_filename(
  7697. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7698. filename = str(filename)
  7699. if filename == "":
  7700. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7701. return 'fail'
  7702. # Update options
  7703. self.app.preferencesUiManager.defaults_read_form()
  7704. self.defaults.propagate_defaults()
  7705. # Save update options
  7706. try:
  7707. self.defaults.write(filename=filename)
  7708. except Exception:
  7709. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7710. return
  7711. if self.defaults["global_open_style"] is False:
  7712. self.app.file_opened.emit("preferences", filename)
  7713. self.app.file_saved.emit("preferences", filename)
  7714. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7715. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7716. """
  7717. Exports a Excellon Object to an Excellon file.
  7718. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7719. :param filename: Path to the Excellon file to save to.
  7720. :param local_use:
  7721. :param use_thread: if to be run in a separate thread
  7722. :return:
  7723. """
  7724. if filename is None:
  7725. if self.defaults["global_last_save_folder"]:
  7726. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7727. else:
  7728. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7729. self.app.log.debug("export_excellon()")
  7730. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7731. self.defaults["excellon_exp_decimals"]
  7732. )
  7733. if local_use is None:
  7734. try:
  7735. obj = self.app.collection.get_by_name(str(obj_name))
  7736. except Exception:
  7737. return "Could not retrieve object: %s" % obj_name
  7738. else:
  7739. obj = local_use
  7740. if not isinstance(obj, ExcellonObject):
  7741. self.inform.emit('[ERROR_NOTCL] %s' %
  7742. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7743. return
  7744. # updated units
  7745. eunits = self.defaults["excellon_exp_units"]
  7746. ewhole = self.defaults["excellon_exp_integer"]
  7747. efract = self.defaults["excellon_exp_decimals"]
  7748. ezeros = self.defaults["excellon_exp_zeros"]
  7749. eformat = self.defaults["excellon_exp_format"]
  7750. slot_type = self.defaults["excellon_exp_slot_type"]
  7751. fc_units = self.defaults['units'].upper()
  7752. if fc_units == 'MM':
  7753. factor = 1 if eunits == 'METRIC' else 0.03937
  7754. else:
  7755. factor = 25.4 if eunits == 'METRIC' else 1
  7756. def make_excellon():
  7757. try:
  7758. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7759. header = 'M48\n'
  7760. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7761. (str(self.app.version), str(self.app.version_date))
  7762. header += ';Filename: %s' % str(obj_name) + '\n'
  7763. header += ';Created on : %s' % time_str + '\n'
  7764. if eformat == 'dec':
  7765. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7766. header += eunits + '\n'
  7767. for tool in obj.tools:
  7768. if eunits == 'METRIC':
  7769. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7770. tool=str(tool),
  7771. dec=2)
  7772. else:
  7773. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7774. tool=str(tool),
  7775. dec=4)
  7776. else:
  7777. if ezeros == 'LZ':
  7778. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7779. form='ndec', e_zeros='LZ', factor=factor,
  7780. slot_type=slot_type)
  7781. header += '%s,%s\n' % (eunits, 'LZ')
  7782. header += format_exc
  7783. for tool in obj.tools:
  7784. if eunits == 'METRIC':
  7785. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7786. float(obj.tools[tool]['tooldia']) * factor,
  7787. tool=str(tool),
  7788. dec=2)
  7789. else:
  7790. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7791. float(obj.tools[tool]['tooldia']) * factor,
  7792. tool=str(tool),
  7793. dec=4)
  7794. else:
  7795. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7796. form='ndec', e_zeros='TZ', factor=factor,
  7797. slot_type=slot_type)
  7798. header += '%s,%s\n' % (eunits, 'TZ')
  7799. header += format_exc
  7800. for tool in obj.tools:
  7801. if eunits == 'METRIC':
  7802. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7803. float(obj.tools[tool]['tooldia']) * factor,
  7804. tool=str(tool),
  7805. dec=2)
  7806. else:
  7807. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7808. float(obj.tools[tool]['tooldia']) * factor,
  7809. tool=str(tool),
  7810. dec=4)
  7811. header += '%\n'
  7812. footer = 'M30\n'
  7813. exported_excellon = header
  7814. exported_excellon += excellon_code
  7815. exported_excellon += footer
  7816. if local_use is None:
  7817. try:
  7818. with open(filename, 'w') as fp:
  7819. fp.write(exported_excellon)
  7820. except PermissionError:
  7821. self.inform.emit('[WARNING] %s' %
  7822. _("Permission denied, saving not possible.\n"
  7823. "Most likely another app is holding the file open and not accessible."))
  7824. return 'fail'
  7825. if self.defaults["global_open_style"] is False:
  7826. self.app.file_opened.emit("Excellon", filename)
  7827. self.app.file_saved.emit("Excellon", filename)
  7828. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7829. else:
  7830. return exported_excellon
  7831. except Exception as e:
  7832. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7833. return 'fail'
  7834. if use_thread is True:
  7835. with self.app.proc_container.new(_("Exporting Excellon")) as proc:
  7836. def job_thread_exc(app_obj):
  7837. ret = make_excellon()
  7838. if ret == 'fail':
  7839. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7840. return
  7841. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7842. else:
  7843. eret = make_excellon()
  7844. if eret == 'fail':
  7845. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7846. return 'fail'
  7847. if local_use is not None:
  7848. return eret
  7849. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7850. """
  7851. Exports a Gerber Object to an Gerber file.
  7852. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7853. :param filename: Path to the Gerber file to save to.
  7854. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7855. When not None, the value will be the actual Gerber object for which to create
  7856. the Gerber code
  7857. :param use_thread: if to be run in a separate thread
  7858. :return:
  7859. """
  7860. if filename is None:
  7861. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7862. is not None else self.defaults["global_last_folder"]
  7863. self.app.log.debug("export_gerber()")
  7864. if local_use is None:
  7865. try:
  7866. obj = self.app.collection.get_by_name(str(obj_name))
  7867. except Exception:
  7868. return 'fail'
  7869. else:
  7870. obj = local_use
  7871. # updated units
  7872. gunits = self.defaults["gerber_exp_units"]
  7873. gwhole = self.defaults["gerber_exp_integer"]
  7874. gfract = self.defaults["gerber_exp_decimals"]
  7875. gzeros = self.defaults["gerber_exp_zeros"]
  7876. fc_units = self.defaults['units'].upper()
  7877. if fc_units == 'MM':
  7878. factor = 1 if gunits == 'MM' else 0.03937
  7879. else:
  7880. factor = 25.4 if gunits == 'MM' else 1
  7881. def make_gerber():
  7882. try:
  7883. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7884. header = 'G04*\n'
  7885. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7886. (str(self.app.version), str(self.app.version_date))
  7887. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7888. header += 'G04 Created on : %s*' % time_str + '\n'
  7889. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7890. header += "%MO{units}*%\n".format(units=gunits)
  7891. for apid in obj.apertures:
  7892. if obj.apertures[apid]['type'] == 'C':
  7893. header += "%ADD{apid}{type},{size}*%\n".format(
  7894. apid=str(apid),
  7895. type='C',
  7896. size=(factor * obj.apertures[apid]['size'])
  7897. )
  7898. elif obj.apertures[apid]['type'] == 'R':
  7899. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7900. apid=str(apid),
  7901. type='R',
  7902. width=(factor * obj.apertures[apid]['width']),
  7903. height=(factor * obj.apertures[apid]['height'])
  7904. )
  7905. elif obj.apertures[apid]['type'] == 'O':
  7906. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7907. apid=str(apid),
  7908. type='O',
  7909. width=(factor * obj.apertures[apid]['width']),
  7910. height=(factor * obj.apertures[apid]['height'])
  7911. )
  7912. header += '\n'
  7913. # obsolete units but some software may need it
  7914. if gunits == 'IN':
  7915. header += 'G70*\n'
  7916. else:
  7917. header += 'G71*\n'
  7918. # Absolute Mode
  7919. header += 'G90*\n'
  7920. header += 'G01*\n'
  7921. # positive polarity
  7922. header += '%LPD*%\n'
  7923. footer = 'M02*\n'
  7924. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7925. exported_gerber = header
  7926. exported_gerber += gerber_code
  7927. exported_gerber += footer
  7928. if local_use is None:
  7929. try:
  7930. with open(filename, 'w') as fp:
  7931. fp.write(exported_gerber)
  7932. except PermissionError:
  7933. self.inform.emit('[WARNING] %s' %
  7934. _("Permission denied, saving not possible.\n"
  7935. "Most likely another app is holding the file open and not accessible."))
  7936. return 'fail'
  7937. if self.defaults["global_open_style"] is False:
  7938. self.app.file_opened.emit("Gerber", filename)
  7939. self.app.file_saved.emit("Gerber", filename)
  7940. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7941. else:
  7942. return exported_gerber
  7943. except Exception as e:
  7944. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7945. return 'fail'
  7946. if use_thread is True:
  7947. with self.app.proc_container.new(_("Exporting Gerber")) as proc:
  7948. def job_thread_grb(app_obj):
  7949. ret = make_gerber()
  7950. if ret == 'fail':
  7951. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7952. return
  7953. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7954. else:
  7955. gret = make_gerber()
  7956. if gret == 'fail':
  7957. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7958. return 'fail'
  7959. if local_use is not None:
  7960. return gret
  7961. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7962. """
  7963. Exports a Geometry Object to an DXF file.
  7964. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7965. :param filename: Path to the DXF file to save to.
  7966. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7967. When not None, the value will be the actual Geometry object for which to create
  7968. the Geometry/DXF code
  7969. :param use_thread: if to be run in a separate thread
  7970. :return:
  7971. """
  7972. if filename is None:
  7973. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7974. is not None else self.defaults["global_last_folder"]
  7975. self.app.log.debug("export_dxf()")
  7976. if local_use is None:
  7977. try:
  7978. obj = self.app.collection.get_by_name(str(obj_name))
  7979. except Exception:
  7980. return 'fail'
  7981. else:
  7982. obj = local_use
  7983. def make_dxf():
  7984. try:
  7985. dxf_code = obj.export_dxf()
  7986. if local_use is None:
  7987. try:
  7988. dxf_code.saveas(filename)
  7989. except PermissionError:
  7990. self.inform.emit('[WARNING] %s' %
  7991. _("Permission denied, saving not possible.\n"
  7992. "Most likely another app is holding the file open and not accessible."))
  7993. return 'fail'
  7994. if self.defaults["global_open_style"] is False:
  7995. self.app.file_opened.emit("DXF", filename)
  7996. self.app.file_saved.emit("DXF", filename)
  7997. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7998. else:
  7999. return dxf_code
  8000. except Exception as e:
  8001. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8002. return 'fail'
  8003. if use_thread is True:
  8004. with self.app.proc_container.new(_("Exporting DXF")) as proc:
  8005. def job_thread_exc(app_obj):
  8006. ret_dxf_val = make_dxf()
  8007. if ret_dxf_val == 'fail':
  8008. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8009. return
  8010. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8011. else:
  8012. ret = make_dxf()
  8013. if ret == 'fail':
  8014. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8015. return
  8016. if local_use is not None:
  8017. return ret
  8018. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8019. """
  8020. Adds a new Geometry Object to the projects and populates
  8021. it with shapes extracted from the SVG file.
  8022. :param plot: If True then the resulting object will be plotted on canvas
  8023. :param filename: Path to the SVG file.
  8024. :param geo_type: Type of FlatCAM object that will be created from SVG
  8025. :param outname: The name given to the resulting FlatCAM object
  8026. :return:
  8027. """
  8028. self.app.log.debug("App.import_svg()")
  8029. obj_type = ""
  8030. if geo_type is None or geo_type == "geometry":
  8031. obj_type = "geometry"
  8032. elif geo_type == "gerber":
  8033. obj_type = "gerber"
  8034. else:
  8035. self.inform.emit('[ERROR_NOTCL] %s' %
  8036. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8037. return
  8038. units = self.defaults['units'].upper()
  8039. def obj_init(geo_obj, app_obj):
  8040. geo_obj.import_svg(filename, obj_type, units=units)
  8041. geo_obj.multigeo = True
  8042. with open(filename) as f:
  8043. file_content = f.read()
  8044. geo_obj.source_file = file_content
  8045. with self.app.proc_container.new(_("Importing SVG")) as proc:
  8046. # Object name
  8047. name = outname or filename.split('/')[-1].split('\\')[-1]
  8048. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8049. if ret == 'fail':
  8050. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8051. return 'fail'
  8052. # Register recent file
  8053. self.app.file_opened.emit("svg", filename)
  8054. # appGUI feedback
  8055. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8056. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8057. """
  8058. Adds a new Geometry Object to the projects and populates
  8059. it with shapes extracted from the DXF file.
  8060. :param filename: Path to the DXF file.
  8061. :param geo_type: Type of FlatCAM object that will be created from DXF
  8062. :param outname: Name for the imported Geometry
  8063. :param plot: If True then the resulting object will be plotted on canvas
  8064. :return:
  8065. """
  8066. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8067. obj_type = ""
  8068. if geo_type is None or geo_type == "geometry":
  8069. obj_type = "geometry"
  8070. elif geo_type == "gerber":
  8071. obj_type = geo_type
  8072. else:
  8073. self.inform.emit('[ERROR_NOTCL] %s' %
  8074. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8075. return
  8076. units = self.defaults['units'].upper()
  8077. def obj_init(geo_obj, app_obj):
  8078. if obj_type == "geometry":
  8079. geo_obj.import_dxf_as_geo(filename, units=units)
  8080. elif obj_type == "gerber":
  8081. geo_obj.import_dxf_as_gerber(filename, units=units)
  8082. else:
  8083. return "fail"
  8084. geo_obj.multigeo = True
  8085. with open(filename) as f:
  8086. file_content = f.read()
  8087. geo_obj.source_file = file_content
  8088. with self.app.proc_container.new(_("Importing DXF")):
  8089. # Object name
  8090. name = outname or filename.split('/')[-1].split('\\')[-1]
  8091. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8092. if ret == 'fail':
  8093. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8094. return 'fail'
  8095. # Register recent file
  8096. self.app.file_opened.emit("dxf", filename)
  8097. # appGUI feedback
  8098. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8099. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8100. """
  8101. Opens a Gerber file, parses it and creates a new object for
  8102. it in the program. Thread-safe.
  8103. :param outname: Name of the resulting object. None causes the
  8104. name to be that of the file. Str.
  8105. :param filename: Gerber file filename
  8106. :type filename: str
  8107. :param plot: boolean, to plot or not the resulting object
  8108. :param from_tcl: True if run from Tcl Shell
  8109. :return: None
  8110. """
  8111. # How the object should be initialized
  8112. def obj_init(gerber_obj, app_obj):
  8113. assert isinstance(gerber_obj, GerberObject), \
  8114. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8115. # Opening the file happens here
  8116. try:
  8117. gerber_obj.parse_file(filename)
  8118. except IOError:
  8119. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8120. return "fail"
  8121. except ParseError as err:
  8122. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8123. app_obj.log.error(str(err))
  8124. return "fail"
  8125. except Exception as e:
  8126. log.debug("App.open_gerber() --> %s" % str(e))
  8127. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8128. msg += traceback.format_exc()
  8129. app_obj.inform.emit(msg)
  8130. return "fail"
  8131. if gerber_obj.is_empty():
  8132. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8133. _("Object is not Gerber file or empty. Aborting object creation."))
  8134. return "fail"
  8135. self.app.log.debug("open_gerber()")
  8136. with self.app.proc_container.new(_("Opening Gerber")):
  8137. # Object name
  8138. name = outname or filename.split('/')[-1].split('\\')[-1]
  8139. # # ## Object creation # ##
  8140. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8141. if ret_val == 'fail':
  8142. if from_tcl:
  8143. filename = self.defaults['global_tcl_path'] + '/' + name
  8144. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8145. if ret_val == 'fail':
  8146. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8147. return 'fail'
  8148. # Register recent file
  8149. self.app.file_opened.emit("gerber", filename)
  8150. # appGUI feedback
  8151. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8152. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8153. """
  8154. Opens an Excellon file, parses it and creates a new object for
  8155. it in the program. Thread-safe.
  8156. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8157. :param filename: Excellon file filename
  8158. :type filename: str
  8159. :param plot: boolean, to plot or not the resulting object
  8160. :param from_tcl: True if run from Tcl Shell
  8161. :return: None
  8162. """
  8163. self.app.log.debug("open_excellon()")
  8164. # How the object should be initialized
  8165. def obj_init(excellon_obj, app_obj):
  8166. try:
  8167. ret = excellon_obj.parse_file(filename=filename)
  8168. if ret == "fail":
  8169. app_obj.log.debug("Excellon parsing failed.")
  8170. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8171. return "fail"
  8172. except IOError:
  8173. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8174. app_obj.log.debug("Could not open Excellon object.")
  8175. return "fail"
  8176. except Exception:
  8177. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8178. msg += traceback.format_exc()
  8179. app_obj.inform.emit(msg)
  8180. return "fail"
  8181. ret = excellon_obj.create_geometry()
  8182. if ret == 'fail':
  8183. app_obj.log.debug("Could not create geometry for Excellon object.")
  8184. return "fail"
  8185. for tool in excellon_obj.tools:
  8186. if excellon_obj.tools[tool]['solid_geometry']:
  8187. return
  8188. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8189. return "fail"
  8190. with self.app.proc_container.new(_("Opening Excellon.")):
  8191. # Object name
  8192. name = outname or filename.split('/')[-1].split('\\')[-1]
  8193. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8194. if ret_val == 'fail':
  8195. if from_tcl:
  8196. filename = self.defaults['global_tcl_path'] + '/' + name
  8197. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8198. if ret_val == 'fail':
  8199. self.inform.emit('[ERROR_NOTCL] %s' %
  8200. _('Open Excellon file failed. Probable not an Excellon file.'))
  8201. return
  8202. # Register recent file
  8203. self.app.file_opened.emit("excellon", filename)
  8204. # appGUI feedback
  8205. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8206. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8207. """
  8208. Opens a G-gcode file, parses it and creates a new object for
  8209. it in the program. Thread-safe.
  8210. :param filename: G-code file filename
  8211. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8212. :param force_parsing:
  8213. :param plot: If True plot the object on canvas
  8214. :param from_tcl: True if run from Tcl Shell
  8215. :return: None
  8216. """
  8217. self.app.log.debug("open_gcode()")
  8218. # How the object should be initialized
  8219. def obj_init(job_obj, app_obj_):
  8220. """
  8221. :param job_obj: the resulting object
  8222. :type app_obj_: App
  8223. """
  8224. assert isinstance(app_obj_, App), \
  8225. "Initializer expected App, got %s" % type(app_obj_)
  8226. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8227. try:
  8228. f = open(filename)
  8229. gcode = f.read()
  8230. f.close()
  8231. except IOError:
  8232. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8233. return "fail"
  8234. job_obj.gcode = gcode
  8235. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8236. if gcode_ret == "fail":
  8237. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8238. return "fail"
  8239. job_obj.create_geometry()
  8240. with self.app.proc_container.new(_("Opening G-Code.")):
  8241. # Object name
  8242. name = outname or filename.split('/')[-1].split('\\')[-1]
  8243. # New object creation and file processing
  8244. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8245. if ret_val == 'fail':
  8246. if from_tcl:
  8247. filename = self.defaults['global_tcl_path'] + '/' + name
  8248. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8249. if ret_val == 'fail':
  8250. self.inform.emit('[ERROR_NOTCL] %s' %
  8251. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8252. "Try to load it from File menu.\n "
  8253. "Attempting to create a FlatCAM CNCJob Object from "
  8254. "G-Code file failed during processing"))
  8255. return "fail"
  8256. # Register recent file
  8257. self.app.file_opened.emit("cncjob", filename)
  8258. # appGUI feedback
  8259. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8260. def open_hpgl2(self, filename, outname=None):
  8261. """
  8262. Opens a HPGL2 file, parses it and creates a new object for
  8263. it in the program. Thread-safe.
  8264. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8265. :param filename: HPGL2 file filename
  8266. :return: None
  8267. """
  8268. filename = filename
  8269. # How the object should be initialized
  8270. def obj_init(geo_obj, app_obj):
  8271. assert isinstance(geo_obj, GeometryObject), \
  8272. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8273. # Opening the file happens here
  8274. obj = HPGL2(self)
  8275. try:
  8276. HPGL2.parse_file(obj, filename)
  8277. except IOError:
  8278. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8279. return "fail"
  8280. except ParseError as err:
  8281. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8282. app_obj.log.error(str(err))
  8283. return "fail"
  8284. except Exception as e:
  8285. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8286. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8287. msg += traceback.format_exc()
  8288. app_obj.inform.emit(msg)
  8289. return "fail"
  8290. geo_obj.multigeo = True
  8291. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8292. geo_obj.tools = deepcopy(obj.tools)
  8293. geo_obj.source_file = deepcopy(obj.source_file)
  8294. del obj
  8295. if not geo_obj.solid_geometry:
  8296. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8297. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8298. return "fail"
  8299. self.app.log.debug("open_hpgl2()")
  8300. with self.app.proc_container.new(_("Opening HPGL2")):
  8301. # Object name
  8302. name = outname or filename.split('/')[-1].split('\\')[-1]
  8303. # # ## Object creation # ##
  8304. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8305. if ret == 'fail':
  8306. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8307. return 'fail'
  8308. # Register recent file
  8309. self.app.file_opened.emit("geometry", filename)
  8310. # appGUI feedback
  8311. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8312. def open_script(self, filename, outname=None, silent=False):
  8313. """
  8314. Opens a Script file, parses it and creates a new object for
  8315. it in the program. Thread-safe.
  8316. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8317. :param filename: Script file filename
  8318. :param silent: If True there will be no messages printed to StatusBar
  8319. :return: None
  8320. """
  8321. def obj_init(script_obj, app_obj):
  8322. assert isinstance(script_obj, ScriptObject), \
  8323. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8324. if silent is False:
  8325. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8326. try:
  8327. script_obj.parse_file(filename)
  8328. except IOError:
  8329. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8330. return "fail"
  8331. except ParseError as err:
  8332. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8333. app_obj.log.error(str(err))
  8334. return "fail"
  8335. except Exception as e:
  8336. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8337. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8338. msg += traceback.format_exc()
  8339. app_obj.inform.emit(msg)
  8340. return "fail"
  8341. self.app.log.debug("open_script()")
  8342. with self.app.proc_container.new(_("Opening TCL Script...")):
  8343. # Object name
  8344. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8345. # Object creation
  8346. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8347. if ret_val == 'fail':
  8348. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8349. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8350. if ret_val == 'fail':
  8351. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8352. return 'fail'
  8353. # Register recent file
  8354. self.app.file_opened.emit("script", filename)
  8355. # appGUI feedback
  8356. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8357. def open_config_file(self, filename, run_from_arg=None):
  8358. """
  8359. Loads a config file from the specified file.
  8360. :param filename: Name of the file from which to load.
  8361. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8362. :return: None
  8363. """
  8364. self.app.log.debug("Opening config file: " + filename)
  8365. if run_from_arg:
  8366. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8367. "Canvas initialization finished in"),
  8368. '%.2f' % self.app.used_time,
  8369. _("Opening FlatCAM Config file.")),
  8370. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8371. color=QtGui.QColor("gray"))
  8372. # # add the tab if it was closed
  8373. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8374. # # first clear previous text in text editor (if any)
  8375. # self.ui.text_editor_tab.code_editor.clear()
  8376. #
  8377. # # Switch plot_area to CNCJob tab
  8378. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8379. # close the Code editor if already open
  8380. if self.app.toggle_codeeditor:
  8381. self.app.on_toggle_code_editor()
  8382. self.app.on_toggle_code_editor()
  8383. try:
  8384. if filename:
  8385. f = QtCore.QFile(filename)
  8386. if f.open(QtCore.QIODevice.ReadOnly):
  8387. stream = QtCore.QTextStream(f)
  8388. code_edited = stream.readAll()
  8389. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8390. f.close()
  8391. except IOError:
  8392. self.app.log.error("Failed to open config file: %s" % filename)
  8393. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8394. return
  8395. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8396. """
  8397. Loads a project from the specified file.
  8398. 1) Loads and parses file
  8399. 2) Registers the file as recently opened.
  8400. 3) Calls on_file_new()
  8401. 4) Updates options
  8402. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8403. 6) Calls plot_all() if plot=True
  8404. :param filename: Name of the file from which to load.
  8405. :param run_from_arg: True if run for arguments
  8406. :param plot: If True plot all objects in the project
  8407. :param cli: Run from command line
  8408. :param from_tcl: True if run from Tcl Sehll
  8409. :return: None
  8410. """
  8411. self.app.log.debug("Opening project: " + filename)
  8412. # block autosaving while a project is loaded
  8413. self.app.block_autosave = True
  8414. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8415. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8416. if cli is None:
  8417. self.app.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8418. if run_from_arg:
  8419. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8420. "Canvas initialization finished in"),
  8421. '%.2f' % self.app.used_time,
  8422. _("Opening FlatCAM Project file.")),
  8423. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8424. color=QtGui.QColor("gray"))
  8425. # Open and parse an uncompressed Project file
  8426. try:
  8427. f = open(filename, 'r')
  8428. except IOError:
  8429. if from_tcl:
  8430. name = filename.split('/')[-1].split('\\')[-1]
  8431. filename = self.defaults['global_tcl_path'] + '/' + name
  8432. try:
  8433. f = open(filename, 'r')
  8434. except IOError:
  8435. self.app.log.error("Failed to open project file: %s" % filename)
  8436. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8437. return
  8438. else:
  8439. self.app.log.error("Failed to open project file: %s" % filename)
  8440. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8441. return
  8442. try:
  8443. d = json.load(f, object_hook=dict2obj)
  8444. except Exception as e:
  8445. self.app.log.error(
  8446. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8447. (filename, str(e)))
  8448. f.close()
  8449. # Open and parse a compressed Project file
  8450. try:
  8451. with lzma.open(filename) as f:
  8452. file_content = f.read().decode('utf-8')
  8453. d = json.loads(file_content, object_hook=dict2obj)
  8454. except Exception as e:
  8455. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8456. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8457. return
  8458. # Clear the current project
  8459. # # NOT THREAD SAFE # ##
  8460. if run_from_arg is True:
  8461. pass
  8462. elif cli is True:
  8463. self.app.delete_selection_shape()
  8464. else:
  8465. self.on_file_new()
  8466. # Project options
  8467. self.app.options.update(d['options'])
  8468. self.app.project_filename = filename
  8469. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8470. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8471. if cli is None:
  8472. self.app.set_screen_units(self.app.options["units"])
  8473. # Re create objects
  8474. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8475. for obj in d['objs']:
  8476. def obj_init(obj_inst, app_inst):
  8477. try:
  8478. obj_inst.from_dict(obj)
  8479. except Exception as e:
  8480. self.app.log('App.open_project() --> ' + str(e))
  8481. return 'fail'
  8482. self.app.log.debug("Recreating from opened project an %s object: %s" %
  8483. (obj['kind'].capitalize(), obj['options']['name']))
  8484. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8485. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8486. if cli is None:
  8487. self.app.set_ui_title(name="{} {}: {}".format(
  8488. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8489. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8490. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8491. self.app.should_we_save = False
  8492. self.app.file_opened.emit("project", filename)
  8493. # restore autosaving after a project was loaded
  8494. self.app.block_autosave = False
  8495. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8496. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8497. if cli is None:
  8498. self.app.set_ui_title(name=self.app.project_filename)
  8499. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8500. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8501. """
  8502. Saves the current project to the specified file.
  8503. :param filename: Name of the file in which to save.
  8504. :type filename: str
  8505. :param quit_action: if the project saving will be followed by an app quit; boolean
  8506. :param silent: if True will not display status messages
  8507. :param from_tcl True is run from Tcl Shell
  8508. :return: None
  8509. """
  8510. self.app.log.debug("save_project()")
  8511. self.app.save_in_progress = True
  8512. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8513. # Capture the latest changes
  8514. # Current object
  8515. try:
  8516. current_object = self.app.collection.get_active()
  8517. if current_object:
  8518. current_object.read_form()
  8519. except Exception as e:
  8520. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8521. # Serialize the whole project
  8522. d = {
  8523. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8524. "options": self.options,
  8525. "version": self.version
  8526. }
  8527. if self.defaults["global_save_compressed"] is True:
  8528. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8529. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8530. # # Write
  8531. f.write(g)
  8532. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8533. else:
  8534. # Open file
  8535. try:
  8536. f = open(filename, 'w')
  8537. except IOError:
  8538. self.app.log.error("Failed to open file for saving: %s", filename)
  8539. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8540. return
  8541. # Write
  8542. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8543. f.close()
  8544. # verification of the saved project
  8545. # Open and parse
  8546. try:
  8547. saved_f = open(filename, 'r')
  8548. except IOError:
  8549. if silent is False:
  8550. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8551. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8552. return
  8553. try:
  8554. saved_d = json.load(saved_f, object_hook=dict2obj)
  8555. except Exception:
  8556. if silent is False:
  8557. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8558. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8559. f.close()
  8560. return
  8561. saved_f.close()
  8562. if silent is False:
  8563. if 'version' in saved_d:
  8564. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8565. else:
  8566. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8567. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8568. tb_settings = QSettings("Open Source", "FlatCAM")
  8569. lock_state = self.app.ui.lock_action.isChecked()
  8570. tb_settings.setValue('toolbar_lock', lock_state)
  8571. # This will write the setting to the platform specific storage.
  8572. del tb_settings
  8573. # if quit:
  8574. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8575. # t.start()
  8576. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8577. def save_source_file(self, obj_name, filename, use_thread=True):
  8578. """
  8579. Exports a FlatCAM Object to an Gerber/Excellon file.
  8580. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8581. :param filename: Path to the Gerber file to save to.
  8582. :param use_thread: if to be run in a separate thread
  8583. :return:
  8584. """
  8585. if filename is None:
  8586. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8587. is not None else self.defaults["global_last_folder"]
  8588. self.app.log.debug("save source file()")
  8589. obj = self.app.collection.get_by_name(obj_name)
  8590. file_string = StringIO(obj.source_file)
  8591. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8592. if file_string.getvalue() == '':
  8593. self.inform.emit('[ERROR_NOTCL] %s' %
  8594. _("Save cancelled because source file is empty. Try to export the file."))
  8595. return 'fail'
  8596. try:
  8597. with open(filename, 'w') as file:
  8598. file.writelines('G04*\n')
  8599. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8600. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8601. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8602. file.writelines('G04 Created on : %s*\n' % time_string)
  8603. for line in file_string:
  8604. file.writelines(line)
  8605. except PermissionError:
  8606. self.inform.emit('[WARNING] %s' %
  8607. _("Permission denied, saving not possible.\n"
  8608. "Most likely another app is holding the file open and not accessible."))
  8609. return 'fail'
  8610. def on_file_savedefaults(self):
  8611. """
  8612. Callback for menu item File->Save Defaults. Saves application default options
  8613. ``self.defaults`` to current_defaults.FlatConfig.
  8614. :return: None
  8615. """
  8616. self.app.preferencesUiManager.save_defaults()
  8617. # end of file