app_Main.py 473 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521
  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(_("The application 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(_("The application 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' % (_("The application 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_howto)
  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"))
  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_howto(self):
  2460. """
  2461. Displays the "about" dialog found in the Menu --> Help.
  2462. :return: None
  2463. """
  2464. class HowtoDialog(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('%s ...' % _("How To"))
  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. # font-weight: bold;
  2512. content = QtWidgets.QLabel(
  2513. "%s<br>"
  2514. "%s<br><br>"
  2515. "%s,<br>"
  2516. "%s<br>"
  2517. "<ul>"
  2518. "<li> &nbsp;%s %s</li>"
  2519. "<li> &nbsp;%s %s</li>"
  2520. "</ul>"
  2521. "<br><br>"
  2522. "%s <br>"
  2523. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2524. (
  2525. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2526. _("Yet it cannot evolve without <b>contributions</b>."),
  2527. _("If you want to see this application grow and become better and better"),
  2528. _("you can <b>contribute</b> to the development yourself by:"),
  2529. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2530. new_features_link,
  2531. _("Bug Reports by providing the steps required to reproduce the bug"),
  2532. bugs_link,
  2533. _("If you like what you have seen so far ..."),
  2534. _("Donations are NOT required."), _("But they are welcomed"),
  2535. donation_link
  2536. )
  2537. )
  2538. content.setOpenExternalLinks(True)
  2539. # palette
  2540. pal = QtGui.QPalette()
  2541. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2542. # layouts
  2543. main_layout = QtWidgets.QVBoxLayout()
  2544. self.setLayout(main_layout)
  2545. tab_layout = QtWidgets.QHBoxLayout()
  2546. buttons_hlay = QtWidgets.QHBoxLayout()
  2547. main_layout.addLayout(tab_layout)
  2548. main_layout.addLayout(buttons_hlay)
  2549. tab_widget = QtWidgets.QTabWidget()
  2550. tab_layout.addWidget(tab_widget)
  2551. closebtn = QtWidgets.QPushButton(_("Close"))
  2552. buttons_hlay.addStretch()
  2553. buttons_hlay.addWidget(closebtn)
  2554. # CONTRIBUTE section
  2555. self.intro_tab = QtWidgets.QWidget()
  2556. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2557. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2558. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2559. self.grid_lay = QtWidgets.QGridLayout()
  2560. self.grid_lay.setHorizontalSpacing(20)
  2561. self.grid_lay.setColumnStretch(0, 0)
  2562. self.grid_lay.setColumnStretch(1, 1)
  2563. intro_wdg = QtWidgets.QWidget()
  2564. intro_wdg.setLayout(self.grid_lay)
  2565. intro_scroll_area = QtWidgets.QScrollArea()
  2566. intro_scroll_area.setWidget(intro_wdg)
  2567. intro_scroll_area.setWidgetResizable(True)
  2568. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2569. intro_scroll_area.setPalette(pal)
  2570. self.grid_lay.addWidget(logo, 0, 0)
  2571. self.grid_lay.addWidget(content, 0, 1)
  2572. self.intro_tab_layout.addWidget(intro_scroll_area)
  2573. # LINKS EXCHANGE section
  2574. self.links_tab = QtWidgets.QWidget()
  2575. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2576. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2577. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2578. self.links_lay = QtWidgets.QHBoxLayout()
  2579. links_wdg = QtWidgets.QWidget()
  2580. links_wdg.setLayout(self.links_lay)
  2581. links_scroll_area = QtWidgets.QScrollArea()
  2582. links_scroll_area.setWidget(links_wdg)
  2583. links_scroll_area.setWidgetResizable(True)
  2584. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2585. links_scroll_area.setPalette(pal)
  2586. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2587. self.links_tab_layout.addWidget(links_scroll_area)
  2588. # HOW TO section
  2589. self.howto_tab = QtWidgets.QWidget()
  2590. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2591. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2592. tab_widget.addTab(self.howto_tab, _("How To's"))
  2593. self.howto_lay = QtWidgets.QHBoxLayout()
  2594. howto_wdg = QtWidgets.QWidget()
  2595. howto_wdg.setLayout(self.howto_lay)
  2596. howto_scroll_area = QtWidgets.QScrollArea()
  2597. howto_scroll_area.setWidget(howto_wdg)
  2598. howto_scroll_area.setWidgetResizable(True)
  2599. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2600. howto_scroll_area.setPalette(pal)
  2601. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2602. self.howto_tab_layout.addWidget(howto_scroll_area)
  2603. # BUTTONS section
  2604. closebtn.clicked.connect(self.accept)
  2605. HowtoDialog(app=self, parent=self.ui).exec_()
  2606. def install_bookmarks(self, book_dict=None):
  2607. """
  2608. Install the bookmarks actions in the Help menu -> Bookmarks
  2609. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2610. :return: None
  2611. """
  2612. if book_dict is None:
  2613. self.defaults["global_bookmarks"].update(
  2614. {
  2615. '1': ['FlatCAM', "http://flatcam.org"],
  2616. '2': ['Backup Site', ""]
  2617. }
  2618. )
  2619. else:
  2620. self.defaults["global_bookmarks"].clear()
  2621. self.defaults["global_bookmarks"].update(book_dict)
  2622. # first try to disconnect if somehow they get connected from elsewhere
  2623. for act in self.ui.menuhelp_bookmarks.actions():
  2624. try:
  2625. act.triggered.disconnect()
  2626. except TypeError:
  2627. pass
  2628. # clear all actions except the last one who is the Bookmark manager
  2629. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2630. pass
  2631. else:
  2632. self.ui.menuhelp_bookmarks.removeAction(act)
  2633. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2634. if self.defaults["global_bookmarks"]:
  2635. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2636. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2637. # the JSON is first making the keys as strings (therefore I have to use strings too
  2638. # or do the conversion :(
  2639. # )
  2640. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2641. # the '10' entry jsut after '1' therefore ordering as strings
  2642. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2643. key=lambda x: int(x[0]))
  2644. for entry, bookmark in sorted_bookmarks:
  2645. title = bookmark[0]
  2646. weblink = bookmark[1]
  2647. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2648. act.setText(title)
  2649. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2650. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2651. if title == 'Backup Site' and weblink == "":
  2652. act.triggered.connect(self.on_backup_site)
  2653. else:
  2654. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2655. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2656. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2657. def on_bookmarks_manager(self):
  2658. """
  2659. Adds the bookmark manager in a Tab in Plot Area
  2660. :return:
  2661. """
  2662. for idx in range(self.ui.plot_tab_area.count()):
  2663. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2664. # there can be only one instance of Bookmark Manager at one time
  2665. return
  2666. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2667. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2668. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2669. # add the tab if it was closed
  2670. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2671. # delete the absolute and relative position and messages in the infobar
  2672. # self.ui.position_label.setText("")
  2673. # self.ui.rel_position_label.setText("")
  2674. # hide coordinates toolbars in the infobar while in DB
  2675. self.ui.coords_toolbar.hide()
  2676. self.ui.delta_coords_toolbar.hide()
  2677. # Switch plot_area to preferences page
  2678. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2679. def on_backup_site(self):
  2680. msgbox = QtWidgets.QMessageBox()
  2681. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2682. "1. FlatCAM.org website is down\n"
  2683. "2. Someone forked FlatCAM project and wants to point\n"
  2684. "to his own website\n\n"
  2685. "If you can't get any informations about the application\n"
  2686. "use the YouTube channel link from the Help menu."))
  2687. msgbox.setWindowTitle(_("Alternative website"))
  2688. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2689. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2690. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2691. msgbox.setDefaultButton(bt_yes)
  2692. msgbox.exec_()
  2693. # response = msgbox.clickedButton()
  2694. def final_save(self):
  2695. """
  2696. Callback for doing a preferences save to file whenever the application is about to quit.
  2697. If the project has changes, it will ask the user to save the project.
  2698. :return: None
  2699. """
  2700. if self.save_in_progress:
  2701. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2702. return
  2703. if self.should_we_save and self.collection.get_list():
  2704. msgbox = QtWidgets.QMessageBox()
  2705. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2706. "\n"
  2707. "Do you want to Save the project?"))
  2708. msgbox.setWindowTitle(_("Save changes"))
  2709. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2710. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2711. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2712. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2713. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2714. msgbox.setDefaultButton(bt_yes)
  2715. msgbox.exec_()
  2716. response = msgbox.clickedButton()
  2717. if response == bt_yes:
  2718. try:
  2719. self.trayIcon.hide()
  2720. except Exception:
  2721. pass
  2722. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2723. elif response == bt_no:
  2724. try:
  2725. self.trayIcon.hide()
  2726. except Exception:
  2727. pass
  2728. self.quit_application()
  2729. elif response == bt_cancel:
  2730. return
  2731. else:
  2732. try:
  2733. self.trayIcon.hide()
  2734. except Exception:
  2735. pass
  2736. self.quit_application()
  2737. def quit_application(self):
  2738. """
  2739. Called (as a pyslot or not) when the application is quit.
  2740. :return: None
  2741. """
  2742. # close editors before quiting the app, if they are open
  2743. if self.geo_editor.editor_active is True:
  2744. self.geo_editor.deactivate()
  2745. try:
  2746. self.geo_editor.disconnect()
  2747. except TypeError:
  2748. pass
  2749. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2750. if self.exc_editor.editor_active is True:
  2751. self.exc_editor.deactivate()
  2752. try:
  2753. self.grb_editor.disconnect()
  2754. except TypeError:
  2755. pass
  2756. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2757. if self.grb_editor.editor_active is True:
  2758. self.grb_editor.deactivate_grb_editor()
  2759. try:
  2760. self.exc_editor.disconnect()
  2761. except TypeError:
  2762. pass
  2763. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2764. # disconnect the mouse events
  2765. if self.is_legacy:
  2766. self.plotcanvas.graph_event_disconnect(self.mm)
  2767. self.plotcanvas.graph_event_disconnect(self.mp)
  2768. self.plotcanvas.graph_event_disconnect(self.mr)
  2769. self.plotcanvas.graph_event_disconnect(self.mdc)
  2770. self.plotcanvas.graph_event_disconnect(self.kp)
  2771. else:
  2772. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2773. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2774. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2775. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2776. self.on_mouse_double_click_over_plot)
  2777. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2778. self.preferencesUiManager.save_defaults(silent=True)
  2779. log.debug("App.quit_application() --> App Defaults saved.")
  2780. if self.cmd_line_headless != 1:
  2781. # save app state to file
  2782. stgs = QSettings("Open Source", "FlatCAM")
  2783. stgs.setValue('saved_gui_state', self.ui.saveState())
  2784. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2785. stgs.setValue(
  2786. 'language',
  2787. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2788. )
  2789. stgs.setValue(
  2790. 'notebook_font_size',
  2791. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2792. )
  2793. stgs.setValue(
  2794. 'axis_font_size',
  2795. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2796. )
  2797. stgs.setValue(
  2798. 'textbox_font_size',
  2799. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2800. )
  2801. stgs.setValue(
  2802. 'hud_font_size',
  2803. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2804. )
  2805. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2806. stgs.setValue(
  2807. 'machinist',
  2808. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2809. )
  2810. # This will write the setting to the platform specific storage.
  2811. del stgs
  2812. log.debug("App.quit_application() --> App UI state saved.")
  2813. # try to quit the Socket opened by ArgsThread class
  2814. try:
  2815. # self.new_launch.thread_exit = True
  2816. # self.new_launch.listener.close()
  2817. self.new_launch.stop.emit()
  2818. except Exception as err:
  2819. log.debug("App.quit_application() --> %s" % str(err))
  2820. # try to quit the QThread that run ArgsThread class
  2821. try:
  2822. # del self.new_launch
  2823. self.listen_th.quit()
  2824. except Exception as e:
  2825. log.debug("App.quit_application() --> %s" % str(e))
  2826. # terminate workers
  2827. # self.workers.__del__()
  2828. self.clear_pool()
  2829. # quit app by signalling for self.kill_app() method
  2830. # self.close_app_signal.emit()
  2831. QtWidgets.qApp.quit()
  2832. sys.exit(0)
  2833. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2834. # we use the following command
  2835. # minor_v = sys.version_info.minor
  2836. # if minor_v < 8:
  2837. # # make sure that the app closes
  2838. # sys.exit(0)
  2839. # else:
  2840. # os._exit(0) # fix to work with Python 3.8
  2841. @staticmethod
  2842. def kill_app():
  2843. QtWidgets.qApp.quit()
  2844. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2845. # we use the following command
  2846. sys.exit(0)
  2847. def on_portable_checked(self, state):
  2848. """
  2849. Callback called when the checkbox in Preferences GUI is checked.
  2850. It will set the application as portable by creating the preferences and recent files in the
  2851. 'config' folder found in the FlatCAM installation folder.
  2852. :param state: boolean, the state of the checkbox when clicked/checked
  2853. :return:
  2854. """
  2855. line_no = 0
  2856. data = None
  2857. if sys.platform != 'win32':
  2858. # this won't work in Linux or MacOS
  2859. return
  2860. # test if the app was frozen and choose the path for the configuration file
  2861. if getattr(sys, "frozen", False) is True:
  2862. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2863. else:
  2864. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2865. config_file = current_data_path + '\\configuration.txt'
  2866. try:
  2867. with open(config_file, 'r') as f:
  2868. try:
  2869. data = f.readlines()
  2870. except Exception as e:
  2871. log.debug('App.__init__() -->%s' % str(e))
  2872. return
  2873. except FileNotFoundError:
  2874. pass
  2875. for line in data:
  2876. line = line.strip('\n')
  2877. param = str(line).rpartition('=')
  2878. if param[0] == 'portable':
  2879. break
  2880. line_no += 1
  2881. if state:
  2882. data[line_no] = 'portable=True\n'
  2883. # create the new defauults files
  2884. # create current_defaults.FlatConfig file if there is none
  2885. try:
  2886. f = open(current_data_path + '/current_defaults.FlatConfig')
  2887. f.close()
  2888. except IOError:
  2889. App.log.debug('Creating empty current_defaults.FlatConfig')
  2890. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2891. json.dump({}, f)
  2892. f.close()
  2893. # create factory_defaults.FlatConfig file if there is none
  2894. try:
  2895. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2896. f.close()
  2897. except IOError:
  2898. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2899. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2900. json.dump({}, f)
  2901. f.close()
  2902. try:
  2903. f = open(current_data_path + '/recent.json')
  2904. f.close()
  2905. except IOError:
  2906. App.log.debug('Creating empty recent.json')
  2907. f = open(current_data_path + '/recent.json', 'w')
  2908. json.dump([], f)
  2909. f.close()
  2910. try:
  2911. fp = open(current_data_path + '/recent_projects.json')
  2912. fp.close()
  2913. except IOError:
  2914. App.log.debug('Creating empty recent_projects.json')
  2915. fp = open(current_data_path + '/recent_projects.json', 'w')
  2916. json.dump([], fp)
  2917. fp.close()
  2918. # save the current defaults to the new defaults file
  2919. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2920. else:
  2921. data[line_no] = 'portable=False\n'
  2922. with open(config_file, 'w') as f:
  2923. f.writelines(data)
  2924. def on_register_files(self, obj_type=None):
  2925. """
  2926. Called whenever there is a need to register file extensions with FlatCAM.
  2927. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2928. :param obj_type: the type of object to be register for.
  2929. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2930. :return: None
  2931. """
  2932. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2933. new_reg_path = 'Software\\Classes\\'
  2934. # find if the current user is admin
  2935. try:
  2936. is_admin = os.getuid() == 0
  2937. except AttributeError:
  2938. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2939. if is_admin is True:
  2940. root_path = winreg.HKEY_LOCAL_MACHINE
  2941. else:
  2942. root_path = winreg.HKEY_CURRENT_USER
  2943. # create the keys
  2944. def set_reg(name, root_pth, new_reg_path_par, value):
  2945. try:
  2946. winreg.CreateKey(root_pth, new_reg_path_par)
  2947. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  2948. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2949. return True
  2950. except WindowsError:
  2951. return False
  2952. # delete key in registry
  2953. def delete_reg(root_pth, reg_path, key_to_del):
  2954. key_to_del_path = reg_path + key_to_del
  2955. try:
  2956. winreg.DeleteKey(root_pth, key_to_del_path)
  2957. return True
  2958. except WindowsError:
  2959. return False
  2960. if obj_type is None or obj_type == 'excellon':
  2961. exc_list = \
  2962. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2963. exc_list = [x for x in exc_list if x != '']
  2964. # register all keys in the Preferences window
  2965. for ext in exc_list:
  2966. new_k = new_reg_path + '.%s' % ext
  2967. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2968. # and unregister those that are no longer in the Preferences windows but are in the file
  2969. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2970. if ext not in exc_list:
  2971. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2972. # now write the updated extensions to the self.defaults
  2973. # new_ext = ''
  2974. # for ext in exc_list:
  2975. # new_ext = new_ext + ext + ', '
  2976. # self.defaults["fa_excellon"] = new_ext
  2977. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2978. if obj_type is None or obj_type == 'gcode':
  2979. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2980. gco_list = [x for x in gco_list if x != '']
  2981. # register all keys in the Preferences window
  2982. for ext in gco_list:
  2983. new_k = new_reg_path + '.%s' % ext
  2984. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2985. # and unregister those that are no longer in the Preferences windows but are in the file
  2986. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2987. if ext not in gco_list:
  2988. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2989. # now write the updated extensions to the self.defaults
  2990. # new_ext = ''
  2991. # for ext in gco_list:
  2992. # new_ext = new_ext + ext + ', '
  2993. # self.defaults["fa_gcode"] = new_ext
  2994. self.inform.emit('[success] %s' %
  2995. _("Selected GCode file extensions registered with FlatCAM."))
  2996. if obj_type is None or obj_type == 'gerber':
  2997. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2998. grb_list = [x for x in grb_list if x != '']
  2999. # register all keys in the Preferences window
  3000. for ext in grb_list:
  3001. new_k = new_reg_path + '.%s' % ext
  3002. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3003. # and unregister those that are no longer in the Preferences windows but are in the file
  3004. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3005. if ext not in grb_list:
  3006. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3007. # now write the updated extensions to the self.defaults
  3008. # new_ext = ''
  3009. # for ext in grb_list:
  3010. # new_ext = new_ext + ext + ', '
  3011. # self.defaults["fa_gerber"] = new_ext
  3012. self.inform.emit('[success] %s' %
  3013. _("Selected Gerber file extensions registered with FlatCAM."))
  3014. def add_extension(self, ext_type):
  3015. """
  3016. Add a file extension to the list for a specific object
  3017. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3018. :return:
  3019. """
  3020. if ext_type == 'excellon':
  3021. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3022. if new_ext == '':
  3023. return
  3024. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3025. if new_ext in old_val:
  3026. return
  3027. old_val.append(new_ext)
  3028. old_val.sort()
  3029. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3030. if ext_type == 'gcode':
  3031. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3032. if new_ext == '':
  3033. return
  3034. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3035. if new_ext in old_val:
  3036. return
  3037. old_val.append(new_ext)
  3038. old_val.sort()
  3039. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3040. if ext_type == 'gerber':
  3041. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3042. if new_ext == '':
  3043. return
  3044. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3045. if new_ext in old_val:
  3046. return
  3047. old_val.append(new_ext)
  3048. old_val.sort()
  3049. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3050. if ext_type == 'keyword':
  3051. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3052. if new_kw == '':
  3053. return
  3054. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3055. if new_kw in old_val:
  3056. return
  3057. old_val.append(new_kw)
  3058. old_val.sort()
  3059. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3060. # update the self.myKeywords so the model is updated
  3061. self.autocomplete_kw_list = \
  3062. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3063. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3064. self.shell.command_line().set_model_data(self.myKeywords)
  3065. def del_extension(self, ext_type):
  3066. """
  3067. Remove a file extension from the list for a specific object
  3068. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3069. :return:
  3070. """
  3071. if ext_type == 'excellon':
  3072. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3073. if new_ext == '':
  3074. return
  3075. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3076. if new_ext not in old_val:
  3077. return
  3078. old_val.remove(new_ext)
  3079. old_val.sort()
  3080. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3081. if ext_type == 'gcode':
  3082. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3083. if new_ext == '':
  3084. return
  3085. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3086. if new_ext not in old_val:
  3087. return
  3088. old_val.remove(new_ext)
  3089. old_val.sort()
  3090. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3091. if ext_type == 'gerber':
  3092. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3093. if new_ext == '':
  3094. return
  3095. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3096. if new_ext not in old_val:
  3097. return
  3098. old_val.remove(new_ext)
  3099. old_val.sort()
  3100. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3101. if ext_type == 'keyword':
  3102. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3103. if new_kw == '':
  3104. return
  3105. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3106. if new_kw not in old_val:
  3107. return
  3108. old_val.remove(new_kw)
  3109. old_val.sort()
  3110. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3111. # update the self.myKeywords so the model is updated
  3112. self.autocomplete_kw_list = \
  3113. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3114. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3115. self.shell.command_line().set_model_data(self.myKeywords)
  3116. def restore_extensions(self, ext_type):
  3117. """
  3118. Restore all file extensions associations with FlatCAM, for a specific object
  3119. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3120. :return:
  3121. """
  3122. if ext_type == 'excellon':
  3123. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3124. # for the ability to open Excellon files with .txt extension
  3125. new_exc_list = deepcopy(self.exc_list)
  3126. try:
  3127. new_exc_list.remove('txt')
  3128. except ValueError:
  3129. pass
  3130. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3131. if ext_type == 'gcode':
  3132. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3133. if ext_type == 'gerber':
  3134. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3135. if ext_type == 'keyword':
  3136. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3137. # update the self.myKeywords so the model is updated
  3138. self.autocomplete_kw_list = self.default_keywords
  3139. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3140. self.shell.commnad_line().set_model_data(self.myKeywords)
  3141. def delete_all_extensions(self, ext_type):
  3142. """
  3143. Delete all file extensions associations with FlatCAM, for a specific object
  3144. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3145. :return:
  3146. """
  3147. if ext_type == 'excellon':
  3148. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3149. if ext_type == 'gcode':
  3150. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3151. if ext_type == 'gerber':
  3152. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3153. if ext_type == 'keyword':
  3154. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3155. # update the self.myKeywords so the model is updated
  3156. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3157. self.shell.command_line().set_model_data(self.myKeywords)
  3158. def on_edit_join(self, name=None):
  3159. """
  3160. Callback for Edit->Join. Joins the selected geometry objects into
  3161. a new one.
  3162. :return: None
  3163. """
  3164. self.defaults.report_usage("on_edit_join()")
  3165. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3166. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3167. geo_type_set = set()
  3168. objs = self.collection.get_selected()
  3169. if len(objs) < 2:
  3170. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3171. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3172. return 'fail'
  3173. for obj in objs:
  3174. geo_type_set.add(obj.multigeo)
  3175. # if len(geo_type_list) == 1 means that all list elements are the same
  3176. if len(geo_type_set) != 1:
  3177. self.inform.emit('[ERROR] %s' %
  3178. _("Failed join. The Geometry objects are of different types.\n"
  3179. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3180. "convert from one to another and retry joining \n"
  3181. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3182. "the result may not be what was expected. \n"
  3183. "Check the generated GCODE."))
  3184. return
  3185. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3186. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3187. if True in geo_type_set:
  3188. def initialize(geo_obj, app):
  3189. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3190. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3191. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3192. for v in geo_obj.tools.values():
  3193. v['data']['name'] = obj_name_multi
  3194. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3195. else:
  3196. def initialize(geo_obj, app):
  3197. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3198. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3199. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3200. for v in geo_obj.tools.values():
  3201. v['data']['name'] = obj_name_single
  3202. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3203. self.should_we_save = True
  3204. def on_edit_join_exc(self):
  3205. """
  3206. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3207. a new Excellon.
  3208. :return: None
  3209. """
  3210. self.defaults.report_usage("on_edit_join_exc()")
  3211. objs = self.collection.get_selected()
  3212. for obj in objs:
  3213. if not isinstance(obj, ExcellonObject):
  3214. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3215. return
  3216. if len(objs) < 2:
  3217. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3218. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3219. return 'fail'
  3220. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3221. def initialize(exc_obj, app):
  3222. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3223. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3224. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3225. self.should_we_save = True
  3226. def on_edit_join_grb(self):
  3227. """
  3228. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3229. a new Gerber object.
  3230. :return: None
  3231. """
  3232. self.defaults.report_usage("on_edit_join_grb()")
  3233. objs = self.collection.get_selected()
  3234. for obj in objs:
  3235. if not isinstance(obj, GerberObject):
  3236. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3237. return
  3238. if len(objs) < 2:
  3239. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3240. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3241. return 'fail'
  3242. def initialize(grb_obj, app):
  3243. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3244. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3245. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3246. self.should_we_save = True
  3247. def on_convert_singlegeo_to_multigeo(self):
  3248. """
  3249. Called for converting a Geometry object from single-geo to multi-geo.
  3250. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3251. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3252. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3253. the solid-geometry of that tool.
  3254. :return: None
  3255. """
  3256. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3257. obj = self.collection.get_active()
  3258. if obj is None:
  3259. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3260. return
  3261. if not isinstance(obj, GeometryObject):
  3262. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3263. return
  3264. obj.multigeo = True
  3265. for tooluid, dict_value in obj.tools.items():
  3266. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3267. if not isinstance(obj.solid_geometry, list):
  3268. obj.solid_geometry = [obj.solid_geometry]
  3269. # obj.solid_geometry[:] = []
  3270. obj.plot()
  3271. self.should_we_save = True
  3272. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3273. def on_convert_multigeo_to_singlegeo(self):
  3274. """
  3275. Called for converting a Geometry object from multi-geo to single-geo.
  3276. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3277. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3278. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3279. the solid-geometry of that tool.
  3280. :return: None
  3281. """
  3282. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3283. obj = self.collection.get_active()
  3284. if obj is None:
  3285. self.inform.emit('[ERROR_NOTCL] %s' %
  3286. _("Failed. Select a Geometry Object and try again."))
  3287. return
  3288. if not isinstance(obj, GeometryObject):
  3289. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3290. (_("Expected a GeometryObject, got"), type(obj)))
  3291. return
  3292. obj.multigeo = False
  3293. total_solid_geometry = []
  3294. for tooluid, dict_value in obj.tools.items():
  3295. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3296. # clear the original geometry
  3297. dict_value['solid_geometry'][:] = []
  3298. obj.solid_geometry = deepcopy(total_solid_geometry)
  3299. obj.plot()
  3300. self.should_we_save = True
  3301. self.inform.emit('[success] %s' %
  3302. _("A Geometry object was converted to SingleGeo type."))
  3303. def on_defaults_dict_change(self, field):
  3304. """
  3305. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3306. Edit -> Preferences tab window.
  3307. :param field: the key of the self.defaults dictionary that was changed.
  3308. :return: None
  3309. """
  3310. self.preferencesUiManager.defaults_write_form_field(field=field)
  3311. if field == "units":
  3312. self.set_screen_units(self.defaults['units'])
  3313. def set_screen_units(self, units):
  3314. """
  3315. Set the FlatCAM units on the status bar.
  3316. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3317. :return: None
  3318. """
  3319. self.ui.units_label.setText("[" + units.lower() + "]")
  3320. def on_toggle_units_click(self):
  3321. try:
  3322. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3323. except (TypeError, AttributeError):
  3324. pass
  3325. if self.defaults["units"] == 'MM':
  3326. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3327. else:
  3328. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3329. self.on_toggle_units(no_pref=True)
  3330. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3331. lambda: self.on_toggle_units(no_pref=False))
  3332. def scale_defaults(self, sfactor, dimensions):
  3333. for dim in dimensions:
  3334. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3335. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3336. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3337. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3338. if not self.defaults[dim] or self.defaults[dim] == '':
  3339. continue
  3340. if isinstance(self.defaults[dim], str):
  3341. try:
  3342. tools_diameters = eval(self.defaults[dim])
  3343. except Exception as e:
  3344. log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3345. continue
  3346. elif isinstance(self.defaults[dim], (float, int)):
  3347. tools_diameters = [self.defaults[dim]]
  3348. else:
  3349. tools_diameters = list(self.defaults[dim])
  3350. if isinstance(tools_diameters, (tuple, list)):
  3351. pass
  3352. elif isinstance(tools_diameters, (int, float)):
  3353. tools_diameters = [self.defaults[dim]]
  3354. else:
  3355. continue
  3356. td_len = len(tools_diameters)
  3357. conv_list = []
  3358. for t in range(td_len):
  3359. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3360. self.defaults[dim] = conv_list
  3361. elif dim in ['global_gridx', 'global_gridy']:
  3362. # format the number of decimals to the one specified in self.decimals
  3363. try:
  3364. val = float(self.defaults[dim]) * sfactor
  3365. except Exception as e:
  3366. log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3367. continue
  3368. self.defaults[dim] = self.dec_format(val, self.decimals)
  3369. else:
  3370. # the number of decimals for the rest is kept unchanged
  3371. if self.defaults[dim]:
  3372. try:
  3373. val = float(self.defaults[dim]) * sfactor
  3374. except Exception as e:
  3375. log.debug(
  3376. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3377. )
  3378. continue
  3379. self.defaults[dim] = self.dec_format(val, self.decimals)
  3380. def on_toggle_units(self, no_pref=False):
  3381. """
  3382. Callback for the Units radio-button change in the Preferences tab.
  3383. Changes the application's default units adn for the project too.
  3384. If changing the project's units, the change propagates to all of
  3385. the objects in the project.
  3386. :return: None
  3387. """
  3388. self.defaults.report_usage("on_toggle_units")
  3389. if self.toggle_units_ignore:
  3390. return
  3391. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3392. # If option is the same, then ignore
  3393. if new_units == self.defaults["units"].upper():
  3394. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3395. return
  3396. # Keys in self.defaults for which to scale their values
  3397. dimensions = [
  3398. # Global
  3399. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3400. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3401. # Gerber Object
  3402. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3403. # Gerber Editor
  3404. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3405. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3406. # Excellon Object
  3407. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3408. # Excellon Editor
  3409. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3410. "excellon_editor_slot_length",
  3411. # Geometry Object
  3412. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3413. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3414. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3415. "geometry_extracut_length", "geometry_z_pdepth",
  3416. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3417. # CNCJob Object
  3418. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3419. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3420. # Isolation Tool
  3421. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3422. # Drilling Tool
  3423. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3424. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3425. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3426. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3427. # NCC Tool
  3428. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3429. "tools_ncc_newdia",
  3430. # Cutout Tool
  3431. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3432. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3433. # Paint Tool
  3434. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3435. # 2Sided Tool
  3436. "tools_2sided_drilldia",
  3437. # Film Tool
  3438. "tools_film_boundary", "tools_film_scale_stroke",
  3439. # Panel Tool
  3440. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3441. "tools_panelize_constrainy",
  3442. # Calculators Tool
  3443. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3444. # Transform Tool
  3445. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3446. "tools_transform_buffer_dis",
  3447. # SolderPaste Tool
  3448. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3449. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3450. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3451. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3452. # Corner Markers Tool
  3453. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3454. # Check Rules Tool
  3455. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3456. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3457. # QRCode Tool
  3458. "tools_qrcode_border_size",
  3459. # Copper Thieving Tool
  3460. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3461. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3462. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3463. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3464. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3465. "tools_copper_thieving_mask_clearance",
  3466. # Fiducials Tool
  3467. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3468. # Calibration Tool
  3469. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3470. # Drills Extraction Tool
  3471. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3472. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3473. # Punch Gerber Tool
  3474. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3475. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3476. # Invert Gerber Tool
  3477. "tools_invert_margin",
  3478. ]
  3479. # The scaling factor depending on choice of units.
  3480. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3481. # Changing project units. Warn user.
  3482. msgbox = QtWidgets.QMessageBox()
  3483. msgbox.setWindowTitle(_("Toggle Units"))
  3484. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3485. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3486. msgbox.setText(_("Changing the units of the project\n"
  3487. "will scale all objects.\n\n"
  3488. "Do you want to continue?"))
  3489. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3490. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3491. msgbox.setDefaultButton(bt_ok)
  3492. msgbox.exec_()
  3493. response = msgbox.clickedButton()
  3494. if response == bt_ok:
  3495. if no_pref is False:
  3496. self.preferencesUiManager.defaults_read_form()
  3497. self.scale_defaults(factor, dimensions)
  3498. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3499. self.defaults["units"] = new_units
  3500. # update the defaults from form, some may assume that the conversion is enough and it's not
  3501. self.on_options_app2project()
  3502. # update the objects
  3503. for obj in self.collection.get_list():
  3504. obj.convert_units(new_units)
  3505. # make that the properties stored in the object are also updated
  3506. self.app_obj.object_changed.emit(obj)
  3507. # rebuild the object UI
  3508. obj.build_ui()
  3509. # change this only if the workspace is active
  3510. if self.defaults['global_workspace'] is True:
  3511. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3512. # adjust the grid values on the main toolbar
  3513. val_x = float(self.defaults['global_gridx']) * factor
  3514. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3515. current = self.collection.get_active()
  3516. if current is not None:
  3517. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3518. if not isinstance(current, GeometryObject):
  3519. current.to_form()
  3520. # replot all objects
  3521. self.plot_all()
  3522. # set the status labels to reflect the current FlatCAM units
  3523. self.set_screen_units(new_units)
  3524. # signal to the app that we changed the object properties and it should save the project
  3525. self.should_we_save = True
  3526. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3527. else:
  3528. # Undo toggling
  3529. self.toggle_units_ignore = True
  3530. if self.defaults['units'].upper() == 'MM':
  3531. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3532. else:
  3533. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3534. self.toggle_units_ignore = False
  3535. # store the grid values so they are not changed in the next step
  3536. val_x = float(self.defaults['global_gridx'])
  3537. val_y = float(self.defaults['global_gridy'])
  3538. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3539. self.preferencesUiManager.defaults_read_form()
  3540. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3541. # in self.defaults from the GUI elements but
  3542. # I don't want it for the grid values, so I update them here
  3543. self.defaults['global_gridx'] = val_x
  3544. self.defaults['global_gridy'] = val_y
  3545. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3546. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3547. def on_deselect_all(self):
  3548. self.collection.set_all_inactive()
  3549. self.delete_selection_shape()
  3550. def on_workspace_modified(self):
  3551. # self.save_defaults(silent=True)
  3552. self.plotcanvas.delete_workspace()
  3553. self.preferencesUiManager.defaults_read_form()
  3554. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3555. def on_workspace(self):
  3556. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3557. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3558. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3559. else:
  3560. self.plotcanvas.delete_workspace()
  3561. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3562. self.preferencesUiManager.defaults_read_form()
  3563. # self.save_defaults(silent=True)
  3564. def on_workspace_toggle(self):
  3565. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3566. try:
  3567. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3568. except TypeError:
  3569. pass
  3570. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3571. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3572. self.on_workspace()
  3573. def on_cursor_type(self, val):
  3574. """
  3575. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3576. :return: None
  3577. """
  3578. self.app_cursor.enabled = False
  3579. if val == 'small':
  3580. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3581. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3582. self.app_cursor = self.plotcanvas.new_cursor()
  3583. else:
  3584. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3585. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3586. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3587. if self.ui.grid_snap_btn.isChecked():
  3588. self.app_cursor.enabled = True
  3589. else:
  3590. self.app_cursor.enabled = False
  3591. def on_tool_add_keypress(self):
  3592. # ## Current application units in Upper Case
  3593. self.units = self.defaults['units'].upper()
  3594. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3595. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3596. if notebook_widget_name == 'properties_tab':
  3597. if self.collection.get_active().kind == 'geometry':
  3598. # Tool add works for Geometry only if Advanced is True in Preferences
  3599. if self.defaults["global_app_level"] == 'a':
  3600. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3601. text='%s:' % _('Enter a Tool Diameter'),
  3602. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3603. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3604. val, ok = tool_add_popup.get_value()
  3605. if ok:
  3606. if float(val) == 0:
  3607. self.inform.emit('[WARNING_NOTCL] %s' %
  3608. _("Please enter a tool diameter with non-zero value, in Float format."))
  3609. return
  3610. self.collection.get_active().on_tool_add(dia=float(val))
  3611. else:
  3612. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3613. else:
  3614. msgbox = QtWidgets.QMessageBox()
  3615. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3616. "Go to Preferences -> General - Show Advanced Options."))
  3617. msgbox.setWindowTitle("Tool adding ...")
  3618. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3619. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3620. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3621. msgbox.setDefaultButton(bt_ok)
  3622. msgbox.exec_()
  3623. # work only if the notebook tab on focus is the Tools_Tab
  3624. if notebook_widget_name == 'tool_tab':
  3625. try:
  3626. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3627. except AttributeError:
  3628. return
  3629. # and only if the tool is NCC Tool
  3630. if tool_widget == self.ncclear_tool.toolName:
  3631. self.ncclear_tool.on_add_tool_by_key()
  3632. # and only if the tool is Paint Area Tool
  3633. elif tool_widget == self.paint_tool.toolName:
  3634. self.paint_tool.on_add_tool_by_key()
  3635. # and only if the tool is Solder Paste Dispensing Tool
  3636. elif tool_widget == self.paste_tool.toolName:
  3637. self.paste_tool.on_add_tool_by_key()
  3638. # and only if the tool is Isolation Tool
  3639. elif tool_widget == self.isolation_tool.toolName:
  3640. self.isolation_tool.on_add_tool_by_key()
  3641. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3642. # See description below.
  3643. def on_delete_keypress(self):
  3644. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3645. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3646. if notebook_widget_name == 'properties_tab':
  3647. if self.collection.get_active().kind == 'geometry':
  3648. self.collection.get_active().on_tool_delete()
  3649. # work only if the notebook tab on focus is the Tools_Tab
  3650. elif notebook_widget_name == 'tool_tab':
  3651. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3652. # and only if the tool is NCC Tool
  3653. if tool_widget == self.ncclear_tool.toolName:
  3654. self.ncclear_tool.on_tool_delete()
  3655. # and only if the tool is Paint Tool
  3656. elif tool_widget == self.paint_tool.toolName:
  3657. self.paint_tool.on_tool_delete()
  3658. # and only if the tool is Solder Paste Dispensing Tool
  3659. elif tool_widget == self.paste_tool.toolName:
  3660. self.paste_tool.on_tool_delete()
  3661. # and only if the tool is Isolation Tool
  3662. elif tool_widget == self.isolation_tool.toolName:
  3663. self.isolation_tool.on_tool_delete()
  3664. else:
  3665. self.on_delete()
  3666. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3667. # some screens you have to be careful where you hover with your mouse.
  3668. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3669. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3670. # Complicated, I know :)
  3671. def on_delete(self, force_deletion=False):
  3672. """
  3673. Delete the currently selected FlatCAMObjs.
  3674. :param force_deletion: used by Tcl command
  3675. :return: None
  3676. """
  3677. self.defaults.report_usage("on_delete()")
  3678. response = None
  3679. bt_ok = None
  3680. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3681. # a geometry object before we update it.
  3682. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3683. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3684. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3685. msgbox = QtWidgets.QMessageBox()
  3686. msgbox.setWindowTitle(_("Delete objects"))
  3687. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3688. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3689. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3690. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3691. "the selected objects?"))
  3692. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3693. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3694. msgbox.setDefaultButton(bt_ok)
  3695. msgbox.exec_()
  3696. response = msgbox.clickedButton()
  3697. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3698. response = bt_ok
  3699. if response == bt_ok:
  3700. if self.collection.get_active():
  3701. self.log.debug("App.on_delete()")
  3702. for obj_active in self.collection.get_selected():
  3703. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3704. if obj_active.kind == 'gerber':
  3705. obj_active.mark_shapes_storage.clear()
  3706. obj_active.mark_shapes.clear(update=True)
  3707. obj_active.mark_shapes.enabled = False
  3708. elif obj_active.kind == 'cncjob':
  3709. try:
  3710. obj_active.text_col.enabled = False
  3711. del obj_active.text_col
  3712. obj_active.annotation.clear(update=True)
  3713. del obj_active.annotation
  3714. obj_active.probing_shapes.clear(update=True)
  3715. except AttributeError as e:
  3716. log.debug(
  3717. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3718. )
  3719. while self.collection.get_selected():
  3720. self.delete_first_selected()
  3721. # make sure that the selection shape is deleted, too
  3722. self.delete_selection_shape()
  3723. # if there are no longer objects delete also the exclusion areas shapes
  3724. if not self.collection.get_list():
  3725. self.exc_areas.clear_shapes()
  3726. self.inform.emit('%s...' % _("Object(s) deleted"))
  3727. else:
  3728. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3729. else:
  3730. self.inform.emit(_("Save the work in Editor and try again ..."))
  3731. def delete_first_selected(self):
  3732. # Keep this for later
  3733. try:
  3734. sel_obj = self.collection.get_active()
  3735. name = sel_obj.options["name"]
  3736. isPlotted = sel_obj.options["plot"]
  3737. except AttributeError:
  3738. self.log.debug("Nothing selected for deletion")
  3739. return
  3740. if self.is_legacy is True:
  3741. # Remove plot only if the object was plotted otherwise delaxes will fail
  3742. if isPlotted:
  3743. try:
  3744. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3745. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3746. except Exception as e:
  3747. log.debug("App.delete_first_selected() --> %s" % str(e))
  3748. self.plotcanvas.auto_adjust_axes()
  3749. # Remove from dictionary
  3750. self.collection.delete_active()
  3751. # Clear form
  3752. self.setup_default_properties_tab()
  3753. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3754. def on_set_origin(self):
  3755. """
  3756. Set the origin to the left mouse click position
  3757. :return: None
  3758. """
  3759. # display the message for the user
  3760. # and ask him to click on the desired position
  3761. self.defaults.report_usage("on_set_origin()")
  3762. def origin_replot():
  3763. def worker_task():
  3764. with self.proc_container.new('%s...' % _("Plotting")):
  3765. for obj in self.collection.get_list():
  3766. obj.plot()
  3767. self.plotcanvas.fit_view()
  3768. if self.is_legacy:
  3769. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3770. else:
  3771. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3772. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3773. self.inform.emit(_('Click to set the origin ...'))
  3774. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3775. # first disconnect it as it may have been used by something else
  3776. try:
  3777. self.replot_signal.disconnect()
  3778. except TypeError:
  3779. pass
  3780. self.replot_signal[list].connect(origin_replot)
  3781. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3782. """
  3783. :param event:
  3784. :param location:
  3785. :param noplot:
  3786. :param use_thread:
  3787. :return:
  3788. """
  3789. noplot_sig = noplot
  3790. def worker_task():
  3791. with self.proc_container.new(_("Setting Origin...")):
  3792. obj_list = self.collection.get_list()
  3793. for obj in obj_list:
  3794. obj.offset((x, y))
  3795. self.app_obj.object_changed.emit(obj)
  3796. # Update the object bounding box options
  3797. a, b, c, d = obj.bounds()
  3798. obj.options['xmin'] = a
  3799. obj.options['ymin'] = b
  3800. obj.options['xmax'] = c
  3801. obj.options['ymax'] = d
  3802. self.inform.emit('[success] %s...' % _('Origin set'))
  3803. for obj in obj_list:
  3804. out_name = obj.options["name"]
  3805. if obj.kind == 'gerber':
  3806. obj.source_file = self.f_handlers.export_gerber(
  3807. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3808. elif obj.kind == 'excellon':
  3809. obj.source_file = self.f_handlers.export_excellon(
  3810. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3811. if noplot_sig is False:
  3812. self.replot_signal.emit([])
  3813. if location is not None:
  3814. if len(location) != 2:
  3815. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3816. return 'fail'
  3817. x, y = location
  3818. if use_thread is True:
  3819. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3820. else:
  3821. worker_task()
  3822. self.should_we_save = True
  3823. return
  3824. if event is not None and event.button == 1:
  3825. if self.is_legacy is False:
  3826. event_pos = event.pos
  3827. else:
  3828. event_pos = (event.xdata, event.ydata)
  3829. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3830. if self.grid_status():
  3831. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3832. else:
  3833. pos = pos_canvas
  3834. x = 0 - pos[0]
  3835. y = 0 - pos[1]
  3836. if use_thread is True:
  3837. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3838. else:
  3839. worker_task()
  3840. self.should_we_save = True
  3841. def on_move2origin(self, use_thread=True):
  3842. """
  3843. Move selected objects to origin.
  3844. :param use_thread: Control if to use threaded operation. Boolean.
  3845. :return:
  3846. """
  3847. def worker_task():
  3848. with self.proc_container.new(_("Moving to Origin...")):
  3849. obj_list = self.collection.get_selected()
  3850. if not obj_list:
  3851. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3852. return
  3853. xminlist = []
  3854. yminlist = []
  3855. # first get a bounding box to fit all
  3856. for obj in obj_list:
  3857. xmin, ymin, xmax, ymax = obj.bounds()
  3858. xminlist.append(xmin)
  3859. yminlist.append(ymin)
  3860. # get the minimum x,y for all objects selected
  3861. x = min(xminlist)
  3862. y = min(yminlist)
  3863. for obj in obj_list:
  3864. obj.offset((-x, -y))
  3865. self.app_obj.object_changed.emit(obj)
  3866. # Update the object bounding box options
  3867. a, b, c, d = obj.bounds()
  3868. obj.options['xmin'] = a
  3869. obj.options['ymin'] = b
  3870. obj.options['xmax'] = c
  3871. obj.options['ymax'] = d
  3872. for obj in obj_list:
  3873. obj.plot()
  3874. for obj in obj_list:
  3875. out_name = obj.options["name"]
  3876. if obj.kind == 'gerber':
  3877. obj.source_file = self.f_handlers.export_gerber(
  3878. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3879. elif obj.kind == 'excellon':
  3880. obj.source_file = self.f_handlers.export_excellon(
  3881. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3882. self.inform.emit('[success] %s...' % _('Origin set'))
  3883. if use_thread is True:
  3884. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3885. else:
  3886. worker_task()
  3887. self.should_we_save = True
  3888. def on_jump_to(self, custom_location=None, fit_center=True):
  3889. """
  3890. Jump to a location by setting the mouse cursor location.
  3891. :param custom_location: Jump to a specified point. (x, y) tuple.
  3892. :param fit_center: If to fit view. Boolean.
  3893. :return:
  3894. """
  3895. self.defaults.report_usage("on_jump_to()")
  3896. if not custom_location:
  3897. dia_box_location = None
  3898. try:
  3899. dia_box_location = eval(self.clipboard.text())
  3900. except Exception:
  3901. pass
  3902. if type(dia_box_location) == tuple:
  3903. dia_box_location = str(dia_box_location)
  3904. else:
  3905. dia_box_location = None
  3906. # dia_box = Dialog_box(title=_("Jump to ..."),
  3907. # label=_("Enter the coordinates in format X,Y:"),
  3908. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3909. # initial_text=dia_box_location)
  3910. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3911. label=_("Enter the coordinates in format X,Y:"),
  3912. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3913. initial_text=dia_box_location,
  3914. reference=self.defaults['global_jump_ref'])
  3915. if dia_box.ok is True:
  3916. try:
  3917. location = eval(dia_box.location)
  3918. if not isinstance(location, tuple):
  3919. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3920. return
  3921. if dia_box.reference == 'rel':
  3922. rel_x = self.mouse[0] + location[0]
  3923. rel_y = self.mouse[1] + location[1]
  3924. location = (rel_x, rel_y)
  3925. self.defaults['global_jump_ref'] = dia_box.reference
  3926. except Exception:
  3927. return
  3928. else:
  3929. return
  3930. else:
  3931. location = custom_location
  3932. self.jump_signal.emit(location)
  3933. if fit_center:
  3934. self.plotcanvas.fit_center(loc=location)
  3935. cursor = QtGui.QCursor()
  3936. if self.is_legacy is False:
  3937. # I don't know where those differences come from but they are constant for the current
  3938. # execution of the application and they are multiples of a value around 0.0263mm.
  3939. # In a random way sometimes they are more sometimes they are less
  3940. # if units == 'MM':
  3941. # cal_factor = 0.0263
  3942. # else:
  3943. # cal_factor = 0.0263 / 25.4
  3944. cal_location = (location[0], location[1])
  3945. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3946. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3947. j_pos = (
  3948. int(canvas_origin.x() + round(jump_loc[0])),
  3949. int(canvas_origin.y() + round(jump_loc[1]))
  3950. )
  3951. cursor.setPos(j_pos[0], j_pos[1])
  3952. else:
  3953. # find the canvas origin which is in the top left corner
  3954. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3955. # determine the coordinates for the lowest left point of the canvas
  3956. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3957. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3958. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3959. # canvas) and the point (width, height) is in the top-right location
  3960. loc = self.plotcanvas.axes.transData.transform_point(location)
  3961. j_pos = (
  3962. int(x0 + loc[0]),
  3963. int(y0 - loc[1])
  3964. )
  3965. cursor.setPos(j_pos[0], j_pos[1])
  3966. self.plotcanvas.mouse = [location[0], location[1]]
  3967. if self.defaults["global_cursor_color_enabled"] is True:
  3968. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3969. else:
  3970. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3971. if self.grid_status():
  3972. # Update cursor
  3973. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3974. symbol='++', edge_color=self.cursor_color_3D,
  3975. edge_width=self.defaults["global_cursor_width"],
  3976. size=self.defaults["global_cursor_size"])
  3977. # Set the relative position label
  3978. dx = location[0] - float(self.rel_point1[0])
  3979. dy = location[1] - float(self.rel_point1[1])
  3980. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3981. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3982. # Set the position label
  3983. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3984. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3985. units = self.defaults["units"].lower()
  3986. self.plotcanvas.text_hud.text = \
  3987. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3988. dx, units, dy, units, location[0], units, location[1], units)
  3989. self.inform.emit('[success] %s' % _("Done."))
  3990. return location
  3991. def on_locate(self, obj, fit_center=True):
  3992. """
  3993. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3994. :param obj: The object on which to locate certain points
  3995. :param fit_center: If to fit view. Boolean.
  3996. :return: A point location. (x, y) tuple.
  3997. """
  3998. self.defaults.report_usage("on_locate()")
  3999. if obj is None:
  4000. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4001. return 'fail'
  4002. class DialogBoxChoice(QtWidgets.QDialog):
  4003. def __init__(self, title=None, icon=None, choice='bl'):
  4004. """
  4005. :param title: string with the window title
  4006. """
  4007. super(DialogBoxChoice, self).__init__()
  4008. self.ok = False
  4009. self.setWindowIcon(icon)
  4010. self.setWindowTitle(str(title))
  4011. self.form = QtWidgets.QFormLayout(self)
  4012. self.ref_radio = RadioSet([
  4013. {"label": _("Bottom-Left"), "value": "bl"},
  4014. {"label": _("Top-Left"), "value": "tl"},
  4015. {"label": _("Bottom-Right"), "value": "br"},
  4016. {"label": _("Top-Right"), "value": "tr"},
  4017. {"label": _("Center"), "value": "c"}
  4018. ], orientation='vertical', stretch=False)
  4019. self.ref_radio.set_value(choice)
  4020. self.form.addRow(self.ref_radio)
  4021. self.button_box = QtWidgets.QDialogButtonBox(
  4022. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4023. Qt.Horizontal, parent=self)
  4024. self.form.addRow(self.button_box)
  4025. self.button_box.accepted.connect(self.accept)
  4026. self.button_box.rejected.connect(self.reject)
  4027. if self.exec_() == QtWidgets.QDialog.Accepted:
  4028. self.ok = True
  4029. self.location_point = self.ref_radio.get_value()
  4030. else:
  4031. self.ok = False
  4032. self.location_point = None
  4033. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4034. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4035. choice=self.defaults['global_locate_pt'])
  4036. if dia_box.ok is True:
  4037. try:
  4038. location_point = dia_box.location_point
  4039. self.defaults['global_locate_pt'] = dia_box.location_point
  4040. except Exception:
  4041. return
  4042. else:
  4043. return
  4044. loc_b = obj.bounds()
  4045. if location_point == 'bl':
  4046. location = (loc_b[0], loc_b[1])
  4047. elif location_point == 'tl':
  4048. location = (loc_b[0], loc_b[3])
  4049. elif location_point == 'br':
  4050. location = (loc_b[2], loc_b[1])
  4051. elif location_point == 'tr':
  4052. location = (loc_b[2], loc_b[3])
  4053. else:
  4054. # center
  4055. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4056. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4057. location = (cx, cy)
  4058. self.locate_signal.emit(location, location_point)
  4059. if fit_center:
  4060. self.plotcanvas.fit_center(loc=location)
  4061. cursor = QtGui.QCursor()
  4062. if self.is_legacy is False:
  4063. # I don't know where those differences come from but they are constant for the current
  4064. # execution of the application and they are multiples of a value around 0.0263mm.
  4065. # In a random way sometimes they are more sometimes they are less
  4066. # if units == 'MM':
  4067. # cal_factor = 0.0263
  4068. # else:
  4069. # cal_factor = 0.0263 / 25.4
  4070. cal_location = (location[0], location[1])
  4071. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4072. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4073. j_pos = (
  4074. int(canvas_origin.x() + round(jump_loc[0])),
  4075. int(canvas_origin.y() + round(jump_loc[1]))
  4076. )
  4077. cursor.setPos(j_pos[0], j_pos[1])
  4078. else:
  4079. # find the canvas origin which is in the top left corner
  4080. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4081. # determine the coordinates for the lowest left point of the canvas
  4082. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4083. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4084. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4085. # canvas) and the point (width, height) is in the top-right location
  4086. loc = self.plotcanvas.axes.transData.transform_point(location)
  4087. j_pos = (
  4088. int(x0 + loc[0]),
  4089. int(y0 - loc[1])
  4090. )
  4091. cursor.setPos(j_pos[0], j_pos[1])
  4092. self.plotcanvas.mouse = [location[0], location[1]]
  4093. if self.defaults["global_cursor_color_enabled"] is True:
  4094. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4095. else:
  4096. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4097. if self.grid_status():
  4098. # Update cursor
  4099. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4100. symbol='++', edge_color=self.cursor_color_3D,
  4101. edge_width=self.defaults["global_cursor_width"],
  4102. size=self.defaults["global_cursor_size"])
  4103. # Set the relative position label
  4104. self.dx = location[0] - float(self.rel_point1[0])
  4105. self.dy = location[1] - float(self.rel_point1[1])
  4106. # Set the position label
  4107. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4108. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4109. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4110. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4111. units = self.defaults["units"].lower()
  4112. self.plotcanvas.text_hud.text = \
  4113. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4114. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4115. self.inform.emit('[success] %s' % _("Done."))
  4116. return location
  4117. def on_copy_command(self):
  4118. """
  4119. Will copy a selection of objects, creating new objects.
  4120. :return:
  4121. """
  4122. self.defaults.report_usage("on_copy_command()")
  4123. def initialize(obj_init, app_obj):
  4124. """
  4125. :param obj_init: the new object
  4126. :type obj_init: class
  4127. :param app_obj: An instance of the App class
  4128. :type app_obj: App
  4129. :return: None
  4130. :rtype:
  4131. """
  4132. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4133. try:
  4134. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4135. except AttributeError:
  4136. pass
  4137. try:
  4138. obj_init.apertures = deepcopy(obj.apertures)
  4139. except AttributeError:
  4140. pass
  4141. try:
  4142. if obj.tools:
  4143. obj_init.tools = deepcopy(obj.tools)
  4144. except Exception as err:
  4145. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4146. try:
  4147. obj_init.source_file = deepcopy(obj.source_file)
  4148. except (AttributeError, TypeError):
  4149. pass
  4150. def initialize_excellon(obj_init, app_obj):
  4151. obj_init.source_file = deepcopy(obj.source_file)
  4152. obj_init.tools = deepcopy(obj.tools)
  4153. # drills are offset, so they need to be deep copied
  4154. obj_init.drills = deepcopy(obj.drills)
  4155. # slots are offset, so they need to be deep copied
  4156. obj_init.slots = deepcopy(obj.slots)
  4157. obj_init.create_geometry()
  4158. if not obj_init.tools:
  4159. app_obj.debug("on_copy_command() --> no excellon tools")
  4160. return 'fail'
  4161. def initialize_script(obj_init, app_obj):
  4162. obj_init.source_file = deepcopy(obj.source_file)
  4163. def initialize_document(obj_init, app_obj):
  4164. obj_init.source_file = deepcopy(obj.source_file)
  4165. for obj in self.collection.get_selected():
  4166. obj_name = obj.options["name"]
  4167. try:
  4168. if isinstance(obj, ExcellonObject):
  4169. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4170. elif isinstance(obj, GerberObject):
  4171. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4172. elif isinstance(obj, GeometryObject):
  4173. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4174. elif isinstance(obj, ScriptObject):
  4175. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4176. elif isinstance(obj, DocumentObject):
  4177. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4178. except Exception as e:
  4179. return "Operation failed: %s" % str(e)
  4180. def on_copy_object2(self, custom_name):
  4181. def initialize_geometry(obj_init, app_obj):
  4182. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4183. try:
  4184. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4185. except AttributeError:
  4186. pass
  4187. try:
  4188. obj_init.apertures = deepcopy(obj.apertures)
  4189. except AttributeError:
  4190. pass
  4191. try:
  4192. if obj.tools:
  4193. obj_init.tools = deepcopy(obj.tools)
  4194. except Exception as ee:
  4195. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4196. def initialize_gerber(obj_init, app_obj):
  4197. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4198. obj_init.apertures = deepcopy(obj.apertures)
  4199. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4200. if not obj_init.apertures:
  4201. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4202. return 'fail'
  4203. def initialize_excellon(obj_init, app_obj):
  4204. obj_init.tools = deepcopy(obj.tools)
  4205. # drills are offset, so they need to be deep copied
  4206. obj_init.drills = deepcopy(obj.drills)
  4207. # slots are offset, so they need to be deep copied
  4208. obj_init.slots = deepcopy(obj.slots)
  4209. obj_init.create_geometry()
  4210. if not obj_init.tools:
  4211. app_obj.debug("on_copy_object2() --> no excellon tools")
  4212. return 'fail'
  4213. for obj in self.collection.get_selected():
  4214. obj_name = obj.options["name"]
  4215. try:
  4216. if isinstance(obj, ExcellonObject):
  4217. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4218. elif isinstance(obj, GerberObject):
  4219. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4220. elif isinstance(obj, GeometryObject):
  4221. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4222. except Exception as er:
  4223. return "Operation failed: %s" % str(er)
  4224. def on_rename_object(self, text):
  4225. """
  4226. Will rename an object.
  4227. :param text: New name for the object.
  4228. :return:
  4229. """
  4230. self.defaults.report_usage("on_rename_object()")
  4231. named_obj = self.collection.get_active()
  4232. for obj in named_obj:
  4233. if obj is list:
  4234. self.on_rename_object(text)
  4235. else:
  4236. try:
  4237. obj.options['name'] = text
  4238. except Exception as e:
  4239. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4240. def convert_any2geo(self):
  4241. """
  4242. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4243. :return:
  4244. """
  4245. self.defaults.report_usage("convert_any2geo()")
  4246. def initialize(obj_init, app):
  4247. obj_init.solid_geometry = obj.solid_geometry
  4248. try:
  4249. obj_init.follow_geometry = obj.follow_geometry
  4250. except AttributeError:
  4251. pass
  4252. try:
  4253. obj_init.apertures = obj.apertures
  4254. except AttributeError:
  4255. pass
  4256. try:
  4257. if obj.tools:
  4258. obj_init.tools = obj.tools
  4259. except AttributeError:
  4260. pass
  4261. def initialize_excellon(obj_init, app_obj):
  4262. # objs = self.collection.get_selected()
  4263. # GeometryObject.merge(objs, obj)
  4264. solid_geo = []
  4265. for tool in obj.tools:
  4266. for geo in obj.tools[tool]['solid_geometry']:
  4267. solid_geo.append(geo)
  4268. obj_init.solid_geometry = deepcopy(solid_geo)
  4269. if not obj_init.solid_geometry:
  4270. app_obj.log("convert_any2geo() failed")
  4271. return 'fail'
  4272. if not self.collection.get_selected():
  4273. log.warning("App.convert_any2geo --> No object selected")
  4274. self.inform.emit('[WARNING_NOTCL] %s' %
  4275. _("No object is selected. Select an object and try again."))
  4276. return
  4277. for obj in self.collection.get_selected():
  4278. obj_name = obj.options["name"]
  4279. try:
  4280. if obj.kind == 'excellon':
  4281. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4282. else:
  4283. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4284. except Exception as e:
  4285. return "Operation failed: %s" % str(e)
  4286. def convert_any2gerber(self):
  4287. """
  4288. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4289. :return:
  4290. """
  4291. def initialize_geometry(obj_init, app_obj):
  4292. apertures = {}
  4293. apid = 0
  4294. apertures[str(apid)] = {}
  4295. apertures[str(apid)]['geometry'] = []
  4296. for obj_orig in obj.solid_geometry:
  4297. new_elem = {}
  4298. new_elem['solid'] = obj_orig
  4299. try:
  4300. new_elem['follow'] = obj_orig.exterior
  4301. except AttributeError:
  4302. pass
  4303. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4304. apertures[str(apid)]['size'] = 0.0
  4305. apertures[str(apid)]['type'] = 'C'
  4306. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4307. obj_init.apertures = deepcopy(apertures)
  4308. if not obj_init.apertures:
  4309. app_obj.log("convert_any2gerber() failed")
  4310. return 'fail'
  4311. def initialize_excellon(obj_init, app_obj):
  4312. apertures = {}
  4313. apid = 10
  4314. for tool in obj.tools:
  4315. apertures[str(apid)] = {}
  4316. apertures[str(apid)]['geometry'] = []
  4317. for geo in obj.tools[tool]['solid_geometry']:
  4318. new_el = {}
  4319. new_el['solid'] = geo
  4320. new_el['follow'] = geo.exterior
  4321. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4322. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4323. apertures[str(apid)]['type'] = 'C'
  4324. apid += 1
  4325. # create solid_geometry
  4326. solid_geometry = []
  4327. for apid in apertures:
  4328. for geo_el in apertures[apid]['geometry']:
  4329. solid_geometry.append(geo_el['solid'])
  4330. solid_geometry = MultiPolygon(solid_geometry)
  4331. solid_geometry = solid_geometry.buffer(0.0000001)
  4332. obj_init.solid_geometry = deepcopy(solid_geometry)
  4333. obj_init.apertures = deepcopy(apertures)
  4334. if not obj_init.apertures:
  4335. app_obj.log("convert_any2gerber() failed")
  4336. return 'fail'
  4337. if not self.collection.get_selected():
  4338. log.warning("App.convert_any2gerber --> No object selected")
  4339. self.inform.emit('[WARNING_NOTCL] %s' %
  4340. _("No object is selected. Select an object and try again."))
  4341. return
  4342. for obj in self.collection.get_selected():
  4343. obj_name = obj.options["name"]
  4344. try:
  4345. if obj.kind == 'excellon':
  4346. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4347. elif obj.kind == 'geometry':
  4348. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4349. else:
  4350. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4351. except Exception as e:
  4352. return "Operation failed: %s" % str(e)
  4353. def convert_any2excellon(self):
  4354. """
  4355. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4356. :return:
  4357. """
  4358. def initialize_geometry(obj_init, app_obj):
  4359. tools = {}
  4360. tooluid = 1
  4361. obj_init.solid_geometry = []
  4362. for geo in obj.solid_geometry:
  4363. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4364. continue
  4365. minx, miny, maxx, maxy = geo.bounds
  4366. new_dia = min([maxx-minx, maxy-miny])
  4367. new_drill = geo.centroid
  4368. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4369. current_tooldias = []
  4370. if tools:
  4371. for tool in tools:
  4372. if tools[tool] and 'tooldia' in tools[tool]:
  4373. current_tooldias.append(tools[tool]['tooldia'])
  4374. if new_dia in current_tooldias:
  4375. digits = app_obj.decimals
  4376. for tool in tools:
  4377. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4378. tools[tool]['drills'].append(new_drill)
  4379. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4380. else:
  4381. tools[tooluid] = {}
  4382. tools[tooluid]['tooldia'] = new_dia
  4383. tools[tooluid]['drills'] = [new_drill]
  4384. tools[tooluid]['slots'] = []
  4385. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4386. tooluid += 1
  4387. try:
  4388. obj_init.solid_geometry.append(new_drill_geo)
  4389. except (TypeError, AttributeError):
  4390. obj_init.solid_geometry = [new_drill_geo]
  4391. obj_init.tools = deepcopy(tools)
  4392. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4393. if not obj_init.solid_geometry:
  4394. return 'fail'
  4395. def initialize_gerber(obj_init, app_obj):
  4396. tools = {}
  4397. tooluid = 1
  4398. digits = app_obj.decimals
  4399. obj_init.solid_geometry = []
  4400. for apid in obj.apertures:
  4401. if 'geometry' in obj.apertures[apid]:
  4402. for geo_dict in obj.apertures[apid]['geometry']:
  4403. if 'follow' in geo_dict:
  4404. if isinstance(geo_dict['follow'], Point):
  4405. geo = geo_dict['solid']
  4406. minx, miny, maxx, maxy = geo.bounds
  4407. new_dia = min([maxx - minx, maxy - miny])
  4408. new_drill = geo.centroid
  4409. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4410. current_tooldias = []
  4411. if tools:
  4412. for tool in tools:
  4413. if tools[tool] and 'tooldia' in tools[tool]:
  4414. current_tooldias.append(
  4415. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4416. )
  4417. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4418. if formatted_new_dia in current_tooldias:
  4419. for tool in tools:
  4420. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4421. if new_drill not in tools[tool]['drills']:
  4422. tools[tool]['drills'].append(new_drill)
  4423. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4424. else:
  4425. tools[tooluid] = {}
  4426. tools[tooluid]['tooldia'] = new_dia
  4427. tools[tooluid]['drills'] = [new_drill]
  4428. tools[tooluid]['slots'] = []
  4429. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4430. tooluid += 1
  4431. try:
  4432. obj_init.solid_geometry.append(new_drill_geo)
  4433. except (TypeError, AttributeError):
  4434. obj_init.solid_geometry = [new_drill_geo]
  4435. elif isinstance(geo_dict['follow'], LineString):
  4436. geo_coords = list(geo_dict['follow'].coords)
  4437. # slots can have only a start and stop point and no intermediate points
  4438. if len(geo_coords) != 2:
  4439. continue
  4440. geo = geo_dict['solid']
  4441. try:
  4442. new_dia = obj.apertures[apid]['size']
  4443. except Exception:
  4444. continue
  4445. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4446. new_slot_geo = geo
  4447. current_tooldias = []
  4448. if tools:
  4449. for tool in tools:
  4450. if tools[tool] and 'tooldia' in tools[tool]:
  4451. current_tooldias.append(
  4452. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4453. )
  4454. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4455. for tool in tools:
  4456. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4457. '%.*f' % (self.decimals, new_dia)):
  4458. if new_slot not in tools[tool]['slots']:
  4459. tools[tool]['slots'].append(new_slot)
  4460. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4461. else:
  4462. tools[tooluid] = {}
  4463. tools[tooluid]['tooldia'] = new_dia
  4464. tools[tooluid]['drills'] = []
  4465. tools[tooluid]['slots'] = [new_slot]
  4466. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4467. tooluid += 1
  4468. try:
  4469. obj_init.solid_geometry.append(new_slot_geo)
  4470. except (TypeError, AttributeError):
  4471. obj_init.solid_geometry = [new_slot_geo]
  4472. obj_init.tools = deepcopy(tools)
  4473. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4474. if not obj_init.solid_geometry:
  4475. return 'fail'
  4476. if not self.collection.get_selected():
  4477. log.warning("App.convert_any2excellon--> No object selected")
  4478. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4479. return
  4480. for obj in self.collection.get_selected():
  4481. obj_name = obj.options["name"]
  4482. try:
  4483. if obj.kind == 'gerber':
  4484. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4485. elif obj.kind == 'geometry':
  4486. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4487. else:
  4488. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4489. except Exception as e:
  4490. return "Operation failed: %s" % str(e)
  4491. def abort_all_tasks(self):
  4492. """
  4493. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4494. on the first possible occasion.
  4495. :return:
  4496. """
  4497. if self.abort_flag is False:
  4498. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4499. self.abort_flag = True
  4500. self.cleanup.emit()
  4501. def app_is_idle(self):
  4502. if self.abort_flag:
  4503. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4504. self.abort_flag = False
  4505. def on_selectall(self):
  4506. """
  4507. Will draw a selection box shape around the selected objects.
  4508. :return:
  4509. """
  4510. self.defaults.report_usage("on_selectall()")
  4511. # delete the possible selection box around a possible selected object
  4512. self.delete_selection_shape()
  4513. for name in self.collection.get_names():
  4514. self.collection.set_active(name)
  4515. curr_sel_obj = self.collection.get_by_name(name)
  4516. # create the selection box around the selected object
  4517. if self.defaults['global_selection_shape'] is True:
  4518. self.draw_selection_shape(curr_sel_obj)
  4519. def on_toggle_preferences(self):
  4520. pref_open = False
  4521. for idx in range(self.ui.plot_tab_area.count()):
  4522. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4523. pref_open = True
  4524. if pref_open:
  4525. for idx in range(self.ui.plot_tab_area.count()):
  4526. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4527. self.ui.plot_tab_area.removeTab(idx)
  4528. break
  4529. self.ui.pref_status_label.setStyleSheet("")
  4530. else:
  4531. self.on_preferences()
  4532. def on_preferences(self):
  4533. """
  4534. Adds the Preferences in a Tab in Plot Area
  4535. :return:
  4536. """
  4537. # add the tab if it was closed
  4538. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4539. # delete the absolute and relative position and messages in the infobar
  4540. # self.ui.position_label.setText("")
  4541. # self.ui.rel_position_label.setText("")
  4542. # hide coordinates toolbars in the infobar while in DB
  4543. self.ui.coords_toolbar.hide()
  4544. self.ui.delta_coords_toolbar.hide()
  4545. # Switch plot_area to preferences page
  4546. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4547. # self.ui.show()
  4548. self.ui.pref_status_label.setStyleSheet("""
  4549. QLabel
  4550. {
  4551. color: black;
  4552. background-color: lightseagreen;
  4553. }
  4554. """
  4555. )
  4556. # detect changes in the preferences
  4557. for idx in range(self.ui.pref_tab_area.count()):
  4558. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4559. try:
  4560. try:
  4561. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4562. except (TypeError, AttributeError):
  4563. pass
  4564. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4565. except AttributeError:
  4566. pass
  4567. try:
  4568. try:
  4569. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4570. except (TypeError, AttributeError):
  4571. pass
  4572. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4573. except AttributeError:
  4574. pass
  4575. try:
  4576. try:
  4577. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4578. except (TypeError, AttributeError):
  4579. pass
  4580. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4581. except AttributeError:
  4582. pass
  4583. try:
  4584. try:
  4585. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4586. except (TypeError, AttributeError):
  4587. pass
  4588. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4589. except AttributeError:
  4590. pass
  4591. try:
  4592. try:
  4593. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4594. except (TypeError, AttributeError):
  4595. pass
  4596. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4597. except AttributeError:
  4598. pass
  4599. def on_tools_database(self, source='app'):
  4600. """
  4601. Adds the Tools Database in a Tab in Plot Area.
  4602. :return:
  4603. """
  4604. for idx in range(self.ui.plot_tab_area.count()):
  4605. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4606. # there can be only one instance of Tools Database at one time
  4607. return
  4608. if source == 'app':
  4609. self.tools_db_tab = ToolsDB2(
  4610. app=self,
  4611. parent=self.ui,
  4612. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4613. )
  4614. elif source == 'ncc':
  4615. self.tools_db_tab = ToolsDB2(
  4616. app=self,
  4617. parent=self.ui,
  4618. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4619. )
  4620. elif source == 'paint':
  4621. self.tools_db_tab = ToolsDB2(
  4622. app=self,
  4623. parent=self.ui,
  4624. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4625. )
  4626. elif source == 'iso':
  4627. self.tools_db_tab = ToolsDB2(
  4628. app=self,
  4629. parent=self.ui,
  4630. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4631. )
  4632. elif source == 'cutout':
  4633. self.tools_db_tab = ToolsDB2(
  4634. app=self,
  4635. parent=self.ui,
  4636. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4637. )
  4638. # add the tab if it was closed
  4639. try:
  4640. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4641. self.tools_db_tab.setObjectName("database_tab")
  4642. except Exception as e:
  4643. log.debug("App.on_tools_database() --> %s" % str(e))
  4644. return
  4645. # delete the absolute and relative position and messages in the infobar
  4646. # self.ui.position_label.setText("")
  4647. # self.ui.rel_position_label.setText("")
  4648. # hide coordinates toolbars in the infobar while in DB
  4649. self.ui.coords_toolbar.hide()
  4650. self.ui.delta_coords_toolbar.hide()
  4651. # Switch plot_area to preferences page
  4652. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4653. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4654. self.tools_db_tab.ui_connect()
  4655. def on_geometry_tool_add_from_db_executed(self, tool):
  4656. """
  4657. Here add the tool from DB in the selected geometry object.
  4658. :return:
  4659. """
  4660. tool_from_db = deepcopy(tool)
  4661. obj = self.collection.get_active()
  4662. if obj.kind == 'geometry':
  4663. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4664. # close the tab and delete it
  4665. for idx in range(self.ui.plot_tab_area.count()):
  4666. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4667. wdg = self.ui.plot_tab_area.widget(idx)
  4668. wdg.deleteLater()
  4669. self.ui.plot_tab_area.removeTab(idx)
  4670. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4671. elif obj.kind == 'gerber':
  4672. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4673. # close the tab and delete it
  4674. for idx in range(self.ui.plot_tab_area.count()):
  4675. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4676. wdg = self.ui.plot_tab_area.widget(idx)
  4677. wdg.deleteLater()
  4678. self.ui.plot_tab_area.removeTab(idx)
  4679. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4680. else:
  4681. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4682. def on_plot_area_tab_closed(self, tab_obj_name):
  4683. """
  4684. Executed whenever a QTab is closed in the Plot Area.
  4685. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4686. :return:
  4687. """
  4688. if tab_obj_name == "preferences_tab":
  4689. self.preferencesUiManager.on_close_preferences_tab()
  4690. elif tab_obj_name == "database_tab":
  4691. # disconnect the signals from the table widget in tab
  4692. self.tools_db_tab.ui_disconnect()
  4693. if self.tools_db_changed_flag is True:
  4694. msgbox = QtWidgets.QMessageBox()
  4695. msgbox.setText(_("One or more Tools are edited.\n"
  4696. "Do you want to update the Tools Database?"))
  4697. msgbox.setWindowTitle(_("Save Tools Database"))
  4698. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4699. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4700. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4701. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4702. msgbox.setDefaultButton(bt_yes)
  4703. msgbox.exec_()
  4704. response = msgbox.clickedButton()
  4705. if response == bt_yes:
  4706. self.tools_db_tab.on_save_tools_db()
  4707. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4708. else:
  4709. self.tools_db_changed_flag = False
  4710. self.inform.emit('')
  4711. return
  4712. self.tools_db_tab.deleteLater()
  4713. elif tab_obj_name == "text_editor_tab":
  4714. self.toggle_codeeditor = False
  4715. elif tab_obj_name == "bookmarks_tab":
  4716. self.book_dialog_tab.rebuild_actions()
  4717. self.book_dialog_tab.deleteLater()
  4718. else:
  4719. pass
  4720. # restore the coords toolbars
  4721. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4722. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4723. def on_flipy(self):
  4724. """
  4725. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4726. :return:
  4727. """
  4728. self.defaults.report_usage("on_flipy()")
  4729. obj_list = self.collection.get_selected()
  4730. xminlist = []
  4731. yminlist = []
  4732. xmaxlist = []
  4733. ymaxlist = []
  4734. if not obj_list:
  4735. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4736. else:
  4737. try:
  4738. # first get a bounding box to fit all
  4739. for obj in obj_list:
  4740. xmin, ymin, xmax, ymax = obj.bounds()
  4741. xminlist.append(xmin)
  4742. yminlist.append(ymin)
  4743. xmaxlist.append(xmax)
  4744. ymaxlist.append(ymax)
  4745. # get the minimum x,y and maximum x,y for all objects selected
  4746. xminimal = min(xminlist)
  4747. yminimal = min(yminlist)
  4748. xmaximal = max(xmaxlist)
  4749. ymaximal = max(ymaxlist)
  4750. px = 0.5 * (xminimal + xmaximal)
  4751. py = 0.5 * (yminimal + ymaximal)
  4752. # execute mirroring
  4753. for obj in obj_list:
  4754. obj.mirror('X', [px, py])
  4755. obj.plot()
  4756. self.app_obj.object_changed.emit(obj)
  4757. self.inform.emit('[success] %s' %
  4758. _("Flip on Y axis done."))
  4759. except Exception as e:
  4760. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4761. return
  4762. def on_flipx(self):
  4763. """
  4764. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4765. :return:
  4766. """
  4767. self.defaults.report_usage("on_flipx()")
  4768. obj_list = self.collection.get_selected()
  4769. xminlist = []
  4770. yminlist = []
  4771. xmaxlist = []
  4772. ymaxlist = []
  4773. if not obj_list:
  4774. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on X axis."))
  4775. else:
  4776. try:
  4777. # first get a bounding box to fit all
  4778. for obj in obj_list:
  4779. xmin, ymin, xmax, ymax = obj.bounds()
  4780. xminlist.append(xmin)
  4781. yminlist.append(ymin)
  4782. xmaxlist.append(xmax)
  4783. ymaxlist.append(ymax)
  4784. # get the minimum x,y and maximum x,y for all objects selected
  4785. xminimal = min(xminlist)
  4786. yminimal = min(yminlist)
  4787. xmaximal = max(xmaxlist)
  4788. ymaximal = max(ymaxlist)
  4789. px = 0.5 * (xminimal + xmaximal)
  4790. py = 0.5 * (yminimal + ymaximal)
  4791. # execute mirroring
  4792. for obj in obj_list:
  4793. obj.mirror('Y', [px, py])
  4794. obj.plot()
  4795. self.app_obj.object_changed.emit(obj)
  4796. self.inform.emit('[success] %s' %
  4797. _("Flip on X axis done."))
  4798. except Exception as e:
  4799. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4800. return
  4801. def on_rotate(self, silent=False, preset=None):
  4802. """
  4803. Executed when Options -> Rotate Selection menu entry is clicked.
  4804. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4805. :param preset: A value to be used as predefined angle for rotation.
  4806. :return:
  4807. """
  4808. self.defaults.report_usage("on_rotate()")
  4809. obj_list = self.collection.get_selected()
  4810. xminlist = []
  4811. yminlist = []
  4812. xmaxlist = []
  4813. ymaxlist = []
  4814. if not obj_list:
  4815. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4816. else:
  4817. if silent is False:
  4818. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4819. min=-360, max=360, decimals=4,
  4820. init_val=float(self.defaults['tools_transform_rotate']))
  4821. num, ok = rotatebox.get_value()
  4822. else:
  4823. num = preset
  4824. ok = True
  4825. if ok:
  4826. try:
  4827. # first get a bounding box to fit all
  4828. for obj in obj_list:
  4829. xmin, ymin, xmax, ymax = obj.bounds()
  4830. xminlist.append(xmin)
  4831. yminlist.append(ymin)
  4832. xmaxlist.append(xmax)
  4833. ymaxlist.append(ymax)
  4834. # get the minimum x,y and maximum x,y for all objects selected
  4835. xminimal = min(xminlist)
  4836. yminimal = min(yminlist)
  4837. xmaximal = max(xmaxlist)
  4838. ymaximal = max(ymaxlist)
  4839. px = 0.5 * (xminimal + xmaximal)
  4840. py = 0.5 * (yminimal + ymaximal)
  4841. for sel_obj in obj_list:
  4842. sel_obj.rotate(-float(num), point=(px, py))
  4843. sel_obj.plot()
  4844. self.app_obj.object_changed.emit(sel_obj)
  4845. self.inform.emit('[success] %s' % _("Rotation done."))
  4846. except Exception as e:
  4847. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4848. return
  4849. def on_skewx(self):
  4850. """
  4851. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4852. :return:
  4853. """
  4854. self.defaults.report_usage("on_skewx()")
  4855. obj_list = self.collection.get_selected()
  4856. xminlist = []
  4857. yminlist = []
  4858. if not obj_list:
  4859. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4860. else:
  4861. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4862. min=-360, max=360, decimals=4,
  4863. init_val=float(self.defaults['tools_transform_skew_x']))
  4864. num, ok = skewxbox.get_value()
  4865. if ok:
  4866. # first get a bounding box to fit all
  4867. for obj in obj_list:
  4868. xmin, ymin, xmax, ymax = obj.bounds()
  4869. xminlist.append(xmin)
  4870. yminlist.append(ymin)
  4871. # get the minimum x,y and maximum x,y for all objects selected
  4872. xminimal = min(xminlist)
  4873. yminimal = min(yminlist)
  4874. for obj in obj_list:
  4875. obj.skew(num, 0, point=(xminimal, yminimal))
  4876. obj.plot()
  4877. self.app_obj.object_changed.emit(obj)
  4878. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4879. def on_skewy(self):
  4880. """
  4881. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4882. :return:
  4883. """
  4884. self.defaults.report_usage("on_skewy()")
  4885. obj_list = self.collection.get_selected()
  4886. xminlist = []
  4887. yminlist = []
  4888. if not obj_list:
  4889. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4890. else:
  4891. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4892. min=-360, max=360, decimals=4,
  4893. init_val=float(self.defaults['tools_transform_skew_y']))
  4894. num, ok = skewybox.get_value()
  4895. if ok:
  4896. # first get a bounding box to fit all
  4897. for obj in obj_list:
  4898. xmin, ymin, xmax, ymax = obj.bounds()
  4899. xminlist.append(xmin)
  4900. yminlist.append(ymin)
  4901. # get the minimum x,y and maximum x,y for all objects selected
  4902. xminimal = min(xminlist)
  4903. yminimal = min(yminlist)
  4904. for obj in obj_list:
  4905. obj.skew(0, num, point=(xminimal, yminimal))
  4906. obj.plot()
  4907. self.app_obj.object_changed.emit(obj)
  4908. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4909. def on_plots_updated(self):
  4910. """
  4911. Callback used to report when the plots have changed.
  4912. Adjust axes and zooms to fit.
  4913. :return: None
  4914. """
  4915. if self.is_legacy is False:
  4916. self.plotcanvas.update()
  4917. else:
  4918. self.plotcanvas.auto_adjust_axes()
  4919. self.on_zoom_fit()
  4920. self.collection.update_view()
  4921. # self.inform.emit(_("Plots updated ..."))
  4922. def on_toolbar_replot(self):
  4923. """
  4924. Callback for toolbar button. Re-plots all objects.
  4925. :return: None
  4926. """
  4927. self.log.debug("on_toolbar_replot()")
  4928. try:
  4929. obj = self.collection.get_active()
  4930. if obj:
  4931. obj.read_form()
  4932. else:
  4933. self.on_zoom_fit()
  4934. except AttributeError as e:
  4935. log.debug("on_toolbar_replot() -> %s" % str(e))
  4936. pass
  4937. self.plot_all()
  4938. def grid_status(self):
  4939. return True if self.ui.grid_snap_btn.isChecked() else False
  4940. def populate_cmenu_grids(self):
  4941. units = self.defaults['units'].lower()
  4942. # for act in self.ui.cmenu_gridmenu.actions():
  4943. # act.triggered.disconnect()
  4944. self.ui.cmenu_gridmenu.clear()
  4945. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4946. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4947. _("Grid On/Off"))
  4948. grid_toggle.setCheckable(True)
  4949. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4950. self.ui.cmenu_gridmenu.addSeparator()
  4951. for grid in sorted_list:
  4952. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4953. "%s" % str(grid))
  4954. action.triggered.connect(self.set_grid)
  4955. self.ui.cmenu_gridmenu.addSeparator()
  4956. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4957. _("Add"))
  4958. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4959. _("Delete"))
  4960. grid_add.triggered.connect(self.on_grid_add)
  4961. grid_delete.triggered.connect(self.on_grid_delete)
  4962. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4963. def set_grid(self):
  4964. menu_action = self.sender()
  4965. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4966. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4967. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4968. def on_grid_add(self):
  4969. # ## Current application units in lower Case
  4970. units = self.defaults['units'].lower()
  4971. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4972. text=_('Enter a Grid Value:'),
  4973. min=0.0000, max=99.9999, decimals=4)
  4974. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4975. val, ok = grid_add_popup.get_value()
  4976. if ok:
  4977. if float(val) == 0:
  4978. self.inform.emit('[WARNING_NOTCL] %s' %
  4979. _("Please enter a grid value with non-zero value, in Float format."))
  4980. return
  4981. else:
  4982. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4983. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4984. self.inform.emit('[success] %s...' % _("New Grid added"))
  4985. else:
  4986. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4987. else:
  4988. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4989. def on_grid_delete(self):
  4990. # ## Current application units in lower Case
  4991. units = self.defaults['units'].lower()
  4992. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4993. text='Enter a Grid Value:',
  4994. min=0.0000, max=99.9999, decimals=4)
  4995. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4996. val, ok = grid_del_popup.get_value()
  4997. if ok:
  4998. if float(val) == 0:
  4999. self.inform.emit('[WARNING_NOTCL] %s' %
  5000. _("Please enter a grid value with non-zero value, in Float format."))
  5001. return
  5002. else:
  5003. try:
  5004. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5005. except ValueError:
  5006. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5007. return
  5008. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5009. else:
  5010. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5011. def on_shortcut_list(self):
  5012. self.defaults.report_usage("on_shortcut_list()")
  5013. # add the tab if it was closed
  5014. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5015. # delete the absolute and relative position and messages in the infobar
  5016. # self.ui.position_label.setText("")
  5017. # self.ui.rel_position_label.setText("")
  5018. # hide coordinates toolbars in the infobar while in DB
  5019. self.ui.coords_toolbar.hide()
  5020. self.ui.delta_coords_toolbar.hide()
  5021. # Switch plot_area to preferences page
  5022. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5023. # self.ui.show()
  5024. def on_select_tab(self, name):
  5025. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5026. if self.ui.splitter.sizes()[0] == 0:
  5027. self.ui.splitter.setSizes([1, 1])
  5028. else:
  5029. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5030. self.ui.splitter.setSizes([0, 1])
  5031. if name == 'project':
  5032. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5033. elif name == 'properties':
  5034. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5035. elif name == 'tool':
  5036. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5037. def on_copy_name(self):
  5038. self.defaults.report_usage("on_copy_name()")
  5039. obj = self.collection.get_active()
  5040. try:
  5041. name = obj.options["name"]
  5042. except AttributeError:
  5043. log.debug("on_copy_name() --> No object selected to copy it's name")
  5044. self.inform.emit('[WARNING_NOTCL] %s' %
  5045. _(" No object selected to copy it's name"))
  5046. return
  5047. self.clipboard.setText(name)
  5048. self.inform.emit(_("Name copied on clipboard ..."))
  5049. def on_mouse_click_over_plot(self, event):
  5050. """
  5051. Default actions are:
  5052. :param event: Contains information about the event, like which button
  5053. was clicked, the pixel coordinates and the axes coordinates.
  5054. :return: None
  5055. """
  5056. self.pos = []
  5057. if self.is_legacy is False:
  5058. event_pos = event.pos
  5059. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5060. # # Set the mouse button for panning
  5061. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5062. else:
  5063. event_pos = (event.xdata, event.ydata)
  5064. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5065. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5066. # So it can receive key presses
  5067. self.plotcanvas.native.setFocus()
  5068. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5069. if self.grid_status():
  5070. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5071. else:
  5072. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5073. try:
  5074. if event.button == 1:
  5075. # Reset here the relative coordinates so there is a new reference on the click position
  5076. if self.rel_point1 is None:
  5077. self.rel_point1 = self.pos
  5078. else:
  5079. self.rel_point2 = copy(self.rel_point1)
  5080. self.rel_point1 = self.pos
  5081. self.on_mouse_move_over_plot(event, origin_click=True)
  5082. except Exception as e:
  5083. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5084. def on_mouse_double_click_over_plot(self, event):
  5085. if event.button == 1:
  5086. self.doubleclick = True
  5087. def on_mouse_move_over_plot(self, event, origin_click=None):
  5088. """
  5089. Callback for the mouse motion event over the plot.
  5090. :param event: Contains information about the event.
  5091. :param origin_click
  5092. :return: None
  5093. """
  5094. if self.is_legacy is False:
  5095. event_pos = event.pos
  5096. if self.defaults["global_pan_button"] == '2':
  5097. pan_button = 2
  5098. else:
  5099. pan_button = 3
  5100. self.event_is_dragging = event.is_dragging
  5101. else:
  5102. event_pos = (event.xdata, event.ydata)
  5103. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5104. if self.defaults["global_pan_button"] == '2':
  5105. pan_button = 3
  5106. else:
  5107. pan_button = 2
  5108. self.event_is_dragging = self.plotcanvas.is_dragging
  5109. # So it can receive key presses but not when the Tcl Shell is active
  5110. if not self.ui.shell_dock.isVisible():
  5111. if not self.plotcanvas.native.hasFocus():
  5112. self.plotcanvas.native.setFocus()
  5113. self.pos_jump = event_pos
  5114. self.ui.popMenu.mouse_is_panning = False
  5115. if origin_click is None:
  5116. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5117. if event.button == pan_button and self.event_is_dragging == 1:
  5118. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5119. if self.ui.popMenu.popup_active:
  5120. self.ui.popMenu.popup_active = False
  5121. return
  5122. self.ui.popMenu.mouse_is_panning = True
  5123. return
  5124. if self.rel_point1 is not None:
  5125. try: # May fail in case mouse not within axes
  5126. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5127. if pos_canvas[0] is None or pos_canvas[1] is None:
  5128. return
  5129. if self.grid_status():
  5130. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5131. # Update cursor
  5132. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5133. symbol='++', edge_color=self.cursor_color_3D,
  5134. edge_width=self.defaults["global_cursor_width"],
  5135. size=self.defaults["global_cursor_size"])
  5136. else:
  5137. pos = (pos_canvas[0], pos_canvas[1])
  5138. self.dx = pos[0] - float(self.rel_point1[0])
  5139. self.dy = pos[1] - float(self.rel_point1[1])
  5140. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5141. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5142. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5143. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5144. units = self.defaults["units"].lower()
  5145. self.plotcanvas.text_hud.text = \
  5146. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5147. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5148. self.mouse = [pos[0], pos[1]]
  5149. if self.defaults['global_selection_shape'] is False:
  5150. self.selection_type = None
  5151. return
  5152. # if the mouse is moved and the LMB is clicked then the action is a selection
  5153. if self.event_is_dragging == 1 and event.button == 1:
  5154. self.delete_selection_shape()
  5155. if self.dx < 0:
  5156. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5157. face_color=self.defaults['global_alt_sel_fill'])
  5158. self.selection_type = False
  5159. elif self.dx >= 0:
  5160. self.draw_moving_selection_shape(self.pos, pos)
  5161. self.selection_type = True
  5162. else:
  5163. self.selection_type = None
  5164. else:
  5165. self.selection_type = None
  5166. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5167. if self.defaults['global_hover']:
  5168. for obj in self.collection.get_list():
  5169. try:
  5170. # select the object(s) only if it is enabled (plotted)
  5171. if obj.options['plot']:
  5172. if obj not in self.collection.get_selected():
  5173. poly_obj = Polygon(
  5174. [(obj.options['xmin'], obj.options['ymin']),
  5175. (obj.options['xmax'], obj.options['ymin']),
  5176. (obj.options['xmax'], obj.options['ymax']),
  5177. (obj.options['xmin'], obj.options['ymax'])]
  5178. )
  5179. if Point(pos).within(poly_obj):
  5180. if obj.isHovering is False:
  5181. obj.isHovering = True
  5182. obj.notHovering = True
  5183. # create the selection box around the selected object
  5184. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5185. else:
  5186. if obj.notHovering is True:
  5187. obj.notHovering = False
  5188. obj.isHovering = False
  5189. self.delete_hover_shape()
  5190. except Exception:
  5191. # the Exception here will happen if we try to select on screen and we have an
  5192. # newly (and empty) just created Geometry or Excellon object that do not have the
  5193. # xmin, xmax, ymin, ymax options.
  5194. # In this case poly_obj creation (see above) will fail
  5195. pass
  5196. except Exception as e:
  5197. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5198. self.ui.position_label.setText("")
  5199. self.ui.rel_position_label.setText("")
  5200. self.mouse = None
  5201. def on_mouse_click_release_over_plot(self, event):
  5202. """
  5203. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5204. and has been registered in ''self.__init__()''.
  5205. :param event: contains information about the event.
  5206. :return:
  5207. """
  5208. if self.is_legacy is False:
  5209. event_pos = event.pos
  5210. right_button = 2
  5211. else:
  5212. event_pos = (event.xdata, event.ydata)
  5213. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5214. right_button = 3
  5215. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5216. if self.grid_status():
  5217. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5218. else:
  5219. pos = (pos_canvas[0], pos_canvas[1])
  5220. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5221. # canvas menu
  5222. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5223. self.ui.popMenu.mouse_is_panning = False
  5224. self.cursor = QtGui.QCursor()
  5225. self.populate_cmenu_grids()
  5226. self.ui.popMenu.popup(self.cursor.pos())
  5227. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5228. # selection and then select a type of selection ("enclosing" or "touching")
  5229. if event.button == 1: # left click
  5230. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5231. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5232. if modifiers == QtCore.Qt.ShiftModifier:
  5233. # do not auto open the Project Tab
  5234. self.click_noproject = True
  5235. self.clipboard.setText(
  5236. self.defaults["global_point_clipboard_format"] %
  5237. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5238. )
  5239. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5240. return
  5241. if self.doubleclick is True:
  5242. self.doubleclick = False
  5243. if self.collection.get_selected():
  5244. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5245. if self.ui.splitter.sizes()[0] == 0:
  5246. self.ui.splitter.setSizes([1, 1])
  5247. try:
  5248. # delete the selection shape(S) as it may be in the way
  5249. self.delete_selection_shape()
  5250. self.delete_hover_shape()
  5251. except Exception as e:
  5252. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5253. return
  5254. else:
  5255. # WORKAROUND for LEGACY MODE
  5256. if self.is_legacy is True:
  5257. # if there is no move on canvas then we have no dragging selection
  5258. if self.dx == 0 or self.dy == 0:
  5259. self.selection_type = None
  5260. if self.selection_type is not None:
  5261. try:
  5262. self.selection_area_handler(self.pos, pos, self.selection_type)
  5263. self.selection_type = None
  5264. except Exception as e:
  5265. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5266. return
  5267. else:
  5268. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5269. if key_modifier == QtCore.Qt.ShiftModifier:
  5270. mod_key = 'Shift'
  5271. elif key_modifier == QtCore.Qt.ControlModifier:
  5272. mod_key = 'Control'
  5273. else:
  5274. mod_key = None
  5275. try:
  5276. if self.command_active is None:
  5277. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5278. # deselect, and if it's not selected then it will be selected
  5279. # If there is no active command (self.command_active is None) then we check if we clicked
  5280. # on a object by checking the bounding limits against mouse click position
  5281. if mod_key == self.defaults["global_mselect_key"]:
  5282. self.select_objects(key='multisel')
  5283. else:
  5284. # If there is no active command (self.command_active is None) then we check if
  5285. # we clicked on a object by checking the bounding limits against mouse click position
  5286. self.select_objects()
  5287. self.delete_hover_shape()
  5288. except Exception as e:
  5289. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5290. return
  5291. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5292. """
  5293. :param start_pos: mouse position when the selection LMB click was done
  5294. :param end_pos: mouse position when the left mouse button is released
  5295. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5296. :return:
  5297. """
  5298. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5299. # delete previous selection shape
  5300. self.delete_selection_shape()
  5301. # make all objects inactive
  5302. self.collection.set_all_inactive()
  5303. for obj in self.collection.get_list():
  5304. try:
  5305. # select the object(s) only if it is enabled (plotted)
  5306. if obj.options['plot']:
  5307. # it's a line without area
  5308. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5309. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5310. # it's a geometry with area
  5311. else:
  5312. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5313. (obj.options['xmax'], obj.options['ymin']),
  5314. (obj.options['xmax'], obj.options['ymax']),
  5315. (obj.options['xmin'], obj.options['ymax'])])
  5316. if poly_obj.is_empty or not poly_obj.is_valid:
  5317. continue
  5318. if sel_type is True:
  5319. if poly_obj.within(poly_selection):
  5320. # create the selection box around the selected object
  5321. if self.defaults['global_selection_shape'] is True:
  5322. self.draw_selection_shape(obj)
  5323. self.collection.set_active(obj.options['name'])
  5324. else:
  5325. if poly_selection.intersects(poly_obj):
  5326. # create the selection box around the selected object
  5327. if self.defaults['global_selection_shape'] is True:
  5328. self.draw_selection_shape(obj)
  5329. self.collection.set_active(obj.options['name'])
  5330. obj.selection_shape_drawn = True
  5331. except Exception as e:
  5332. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5333. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5334. # In this case poly_obj creation (see above) will fail
  5335. log.debug("App.selection_area_handler() --> %s" % str(e))
  5336. def select_objects(self, key=None):
  5337. """
  5338. Will select objects clicked on canvas
  5339. :param key: for future use in cumulative selection
  5340. :return:
  5341. """
  5342. # list where we store the overlapped objects under our mouse left click position
  5343. if key is None:
  5344. self.objects_under_the_click_list = []
  5345. # Populate the list with the overlapped objects on the click position
  5346. curr_x, curr_y = self.pos
  5347. for obj in self.all_objects_list:
  5348. # ScriptObject and DocumentObject objects can't be selected
  5349. if obj.kind == 'script' or obj.kind == 'document':
  5350. continue
  5351. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5352. continue
  5353. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5354. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5355. if obj.options['name'] not in self.objects_under_the_click_list:
  5356. if obj.options['plot']:
  5357. # add objects to the objects_under_the_click list only if the object is plotted
  5358. # (active and not disabled)
  5359. self.objects_under_the_click_list.append(obj.options['name'])
  5360. try:
  5361. if self.objects_under_the_click_list:
  5362. curr_sel_obj = self.collection.get_active()
  5363. # case when there is only an object under the click and we toggle it
  5364. if len(self.objects_under_the_click_list) == 1:
  5365. if curr_sel_obj is None:
  5366. self.collection.set_active(self.objects_under_the_click_list[0])
  5367. curr_sel_obj = self.collection.get_active()
  5368. # create the selection box around the selected object
  5369. if self.defaults['global_selection_shape'] is True:
  5370. self.draw_selection_shape(curr_sel_obj)
  5371. curr_sel_obj.selection_shape_drawn = True
  5372. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5373. self.collection.on_objects_selection(False)
  5374. self.delete_selection_shape()
  5375. curr_sel_obj.selection_shape_drawn = False
  5376. self.collection.set_active(self.objects_under_the_click_list[0])
  5377. curr_sel_obj = self.collection.get_active()
  5378. # create the selection box around the selected object
  5379. if self.defaults['global_selection_shape'] is True:
  5380. self.draw_selection_shape(curr_sel_obj)
  5381. curr_sel_obj.selection_shape_drawn = True
  5382. self.selected_message(curr_sel_obj=curr_sel_obj)
  5383. elif curr_sel_obj.selection_shape_drawn is False:
  5384. if self.defaults['global_selection_shape'] is True:
  5385. self.draw_selection_shape(curr_sel_obj)
  5386. curr_sel_obj.selection_shape_drawn = True
  5387. else:
  5388. self.collection.on_objects_selection(False)
  5389. self.delete_selection_shape()
  5390. if self.call_source != 'app':
  5391. self.call_source = 'app'
  5392. self.selected_message(curr_sel_obj=curr_sel_obj)
  5393. else:
  5394. # If there is no selected object
  5395. # make active the first element of the overlapped objects list
  5396. if self.collection.get_active() is None:
  5397. self.collection.set_active(self.objects_under_the_click_list[0])
  5398. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5399. name_sel_obj = self.collection.get_active().options['name']
  5400. # In case that there is a selected object but it is not in the overlapped object list
  5401. # make that object inactive and activate the first element in the overlapped object list
  5402. if name_sel_obj not in self.objects_under_the_click_list:
  5403. self.collection.set_inactive(name_sel_obj)
  5404. name_sel_obj = self.objects_under_the_click_list[0]
  5405. self.collection.set_active(name_sel_obj)
  5406. else:
  5407. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5408. self.collection.set_all_inactive()
  5409. self.collection.set_active(
  5410. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5411. curr_sel_obj = self.collection.get_active()
  5412. # delete the possible selection box around a possible selected object
  5413. self.delete_selection_shape()
  5414. curr_sel_obj.selection_shape_drawn = False
  5415. # create the selection box around the selected object
  5416. if self.defaults['global_selection_shape'] is True:
  5417. self.draw_selection_shape(curr_sel_obj)
  5418. curr_sel_obj.selection_shape_drawn = True
  5419. self.selected_message(curr_sel_obj=curr_sel_obj)
  5420. else:
  5421. # deselect everything
  5422. self.collection.on_objects_selection(False)
  5423. # delete the possible selection box around a possible selected object
  5424. self.delete_selection_shape()
  5425. for o in self.collection.get_list():
  5426. o.selection_shape_drawn = False
  5427. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5428. # only when working on App
  5429. if self.call_source == 'app':
  5430. if self.click_noproject is False:
  5431. # if the Tool Tab is in focus don't change focus to Project Tab
  5432. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5433. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5434. else:
  5435. # restore auto open the Project Tab
  5436. self.click_noproject = False
  5437. # delete any text in the status bar, implicitly the last object name that was selected
  5438. # self.inform.emit("")
  5439. else:
  5440. self.call_source = 'app'
  5441. except Exception as e:
  5442. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5443. def selected_message(self, curr_sel_obj):
  5444. if curr_sel_obj:
  5445. if curr_sel_obj.kind == 'gerber':
  5446. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5447. color='green',
  5448. name=str(curr_sel_obj.options['name']),
  5449. tx=_("selected"))
  5450. )
  5451. elif curr_sel_obj.kind == 'excellon':
  5452. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5453. color='brown',
  5454. name=str(curr_sel_obj.options['name']),
  5455. tx=_("selected"))
  5456. )
  5457. elif curr_sel_obj.kind == 'cncjob':
  5458. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5459. color='blue',
  5460. name=str(curr_sel_obj.options['name']),
  5461. tx=_("selected"))
  5462. )
  5463. elif curr_sel_obj.kind == 'geometry':
  5464. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5465. color='red',
  5466. name=str(curr_sel_obj.options['name']),
  5467. tx=_("selected"))
  5468. )
  5469. def delete_hover_shape(self):
  5470. self.hover_shapes.clear()
  5471. self.hover_shapes.redraw()
  5472. def draw_hover_shape(self, sel_obj, color=None):
  5473. """
  5474. :param sel_obj: The object for which the hover shape must be drawn
  5475. :param color: The color of the hover shape
  5476. :return: None
  5477. """
  5478. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5479. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5480. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5481. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5482. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5483. if self.defaults['units'].upper() == 'MM':
  5484. hover_rect = hover_rect.buffer(-0.1)
  5485. hover_rect = hover_rect.buffer(0.2)
  5486. else:
  5487. hover_rect = hover_rect.buffer(-0.00393)
  5488. hover_rect = hover_rect.buffer(0.00787)
  5489. # if color:
  5490. # face = Color(color)
  5491. # face.alpha = 0.2
  5492. # outline = Color(color, alpha=0.8)
  5493. # else:
  5494. # face = Color(self.defaults['global_sel_fill'])
  5495. # face.alpha = 0.2
  5496. # outline = self.defaults['global_sel_line']
  5497. if color:
  5498. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5499. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5500. else:
  5501. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5502. outline = self.defaults['global_sel_line']
  5503. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5504. if self.is_legacy is True:
  5505. self.hover_shapes.redraw()
  5506. def delete_selection_shape(self):
  5507. self.move_tool.sel_shapes.clear()
  5508. self.move_tool.sel_shapes.redraw()
  5509. def draw_selection_shape(self, sel_obj, color=None):
  5510. """
  5511. Will draw a selection shape around the selected object.
  5512. :param sel_obj: The object for which the selection shape must be drawn
  5513. :param color: The color for the selection shape.
  5514. :return: None
  5515. """
  5516. if sel_obj is None:
  5517. return
  5518. # it's a line without area
  5519. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5520. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5521. # it's a geometry with area
  5522. else:
  5523. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5524. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5525. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5526. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5527. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5528. b_sel_rect = None
  5529. try:
  5530. if self.defaults['units'].upper() == 'MM':
  5531. b_sel_rect = sel_rect.buffer(-0.1)
  5532. b_sel_rect = b_sel_rect.buffer(0.2)
  5533. else:
  5534. b_sel_rect = sel_rect.buffer(-0.00393)
  5535. b_sel_rect = b_sel_rect.buffer(0.00787)
  5536. except Exception:
  5537. pass
  5538. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5539. b_sel_rect = sel_rect
  5540. if color:
  5541. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5542. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5543. else:
  5544. if self.is_legacy is False:
  5545. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5546. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5547. else:
  5548. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5549. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5550. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5551. color=outline,
  5552. face_color=face,
  5553. update=True,
  5554. layer=0,
  5555. tolerance=None))
  5556. if self.is_legacy is True:
  5557. self.move_tool.sel_shapes.redraw()
  5558. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5559. """
  5560. Will draw a selection shape when dragging mouse on canvas.
  5561. :param old_coords: Old coordinates
  5562. :param coords: New coordinates
  5563. :param kwargs: Keyword arguments
  5564. :return:
  5565. """
  5566. if 'color' in kwargs:
  5567. color = kwargs['color']
  5568. else:
  5569. color = self.defaults['global_sel_line']
  5570. if 'face_color' in kwargs:
  5571. face_color = kwargs['face_color']
  5572. else:
  5573. face_color = self.defaults['global_sel_fill']
  5574. if 'face_alpha' in kwargs:
  5575. face_alpha = kwargs['face_alpha']
  5576. else:
  5577. face_alpha = 0.3
  5578. x0, y0 = old_coords
  5579. x1, y1 = coords
  5580. pt1 = (x0, y0)
  5581. pt2 = (x1, y0)
  5582. pt3 = (x1, y1)
  5583. pt4 = (x0, y1)
  5584. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5585. # color_t = Color(face_color)
  5586. # color_t.alpha = face_alpha
  5587. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5588. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5589. layer=0, tolerance=None)
  5590. if self.is_legacy is True:
  5591. self.move_tool.sel_shapes.redraw()
  5592. def obj_properties(self):
  5593. """
  5594. Will launch the object Properties Tool
  5595. :return:
  5596. """
  5597. self.defaults.report_usage("obj_properties()")
  5598. self.properties_tool.run(toggle=False)
  5599. def on_project_context_save(self):
  5600. """
  5601. Wrapper, will save the object function of it's type
  5602. :return:
  5603. """
  5604. sel_objects = self.collection.get_selected()
  5605. len_objects = len(sel_objects)
  5606. cnt = 0
  5607. if len_objects > 1:
  5608. for o in sel_objects:
  5609. if o.kind == 'cncjob':
  5610. cnt += 1
  5611. if len_objects == cnt:
  5612. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5613. _filter_ = self.defaults['cncjob_save_filters'] + \
  5614. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5615. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5616. try:
  5617. filename, _f = FCFileSaveDialog.get_saved_filename(
  5618. caption=_("Export Code ..."),
  5619. directory=dir_file_to_save,
  5620. ext_filter=_filter_
  5621. )
  5622. except TypeError:
  5623. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5624. ext_filter=_filter_)
  5625. filename = filename.rpartition('/')[0]
  5626. for ob in sel_objects:
  5627. ob.read_form()
  5628. fname = '%s/%s' % (filename, ob.options['name'])
  5629. ob.export_gcode_handler(fname, is_gcode=True)
  5630. return
  5631. obj = self.collection.get_active()
  5632. if type(obj) == GeometryObject:
  5633. self.on_file_exportdxf()
  5634. elif type(obj) == ExcellonObject:
  5635. self.on_file_saveexcellon()
  5636. elif type(obj) == CNCJobObject:
  5637. obj.on_exportgcode_button_click()
  5638. elif type(obj) == GerberObject:
  5639. self.on_file_savegerber()
  5640. elif type(obj) == ScriptObject:
  5641. self.on_file_savescript()
  5642. elif type(obj) == DocumentObject:
  5643. self.on_file_savedocument()
  5644. def obj_move(self):
  5645. """
  5646. Callback for the Move menu entry in various Context Menu's.
  5647. :return:
  5648. """
  5649. self.defaults.report_usage("obj_move()")
  5650. self.move_tool.run(toggle=False)
  5651. # ###############################################################################################################
  5652. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5653. # ###############################################################################################################
  5654. def init_code_editor(self, name):
  5655. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5656. # add the tab if it was closed
  5657. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5658. self.text_editor_tab.setObjectName('text_editor_tab')
  5659. # delete the absolute and relative position and messages in the infobar
  5660. # self.ui.position_label.setText("")
  5661. # self.ui.rel_position_label.setText("")
  5662. # hide coordinates toolbars in the infobar while in DB
  5663. self.ui.coords_toolbar.hide()
  5664. self.ui.delta_coords_toolbar.hide()
  5665. self.toggle_codeeditor = True
  5666. self.text_editor_tab.code_editor.completer_enable = False
  5667. self.text_editor_tab.buttonRun.hide()
  5668. # make sure to keep a reference to the code editor
  5669. self.reference_code_editor = self.text_editor_tab.code_editor
  5670. # Switch plot_area to CNCJob tab
  5671. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5672. def on_view_source(self):
  5673. """
  5674. Called when the user wants to see the source file of the selected object
  5675. :return:
  5676. """
  5677. try:
  5678. obj = self.collection.get_active()
  5679. except Exception as e:
  5680. log.debug("App.on_view_source() --> %s" % str(e))
  5681. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5682. return 'fail'
  5683. if obj is None:
  5684. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5685. return 'fail'
  5686. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5687. self.proc_container.view.set_busy(_("Loading..."))
  5688. flt = "All Files (*.*)"
  5689. if obj.kind == 'gerber':
  5690. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5691. elif obj.kind == 'excellon':
  5692. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5693. elif obj.kind == 'cncjob':
  5694. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5695. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5696. # add the tab if it was closed
  5697. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5698. self.source_editor_tab.setObjectName('source_editor_tab')
  5699. # delete the absolute and relative position and messages in the infobar
  5700. # self.ui.position_label.setText("")
  5701. # self.ui.rel_position_label.setText("")
  5702. # hide coordinates toolbars in the infobar while in DB
  5703. self.ui.coords_toolbar.hide()
  5704. self.ui.delta_coords_toolbar.hide()
  5705. self.source_editor_tab.code_editor.completer_enable = False
  5706. self.source_editor_tab.buttonRun.hide()
  5707. # Switch plot_area to CNCJob tab
  5708. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5709. try:
  5710. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5711. except TypeError:
  5712. pass
  5713. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5714. try:
  5715. self.source_editor_tab.buttonSave.clicked.disconnect()
  5716. except TypeError:
  5717. pass
  5718. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5719. # then append the text from GCode to the text editor
  5720. if obj.kind == 'cncjob':
  5721. try:
  5722. file = obj.export_gcode(to_file=True)
  5723. if file == 'fail':
  5724. return 'fail'
  5725. except AttributeError:
  5726. self.inform.emit('[WARNING_NOTCL] %s' %
  5727. _("There is no selected object for which to see it's source file code."))
  5728. return 'fail'
  5729. else:
  5730. try:
  5731. file = StringIO(obj.source_file)
  5732. except (AttributeError, TypeError):
  5733. self.inform.emit('[WARNING_NOTCL] %s' %
  5734. _("There is no selected object for which to see it's source file code."))
  5735. return 'fail'
  5736. self.source_editor_tab.t_frame.hide()
  5737. try:
  5738. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5739. except Exception as e:
  5740. log.debug('App.on_view_source() -->%s' % str(e))
  5741. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5742. return
  5743. self.source_editor_tab.t_frame.show()
  5744. self.proc_container.view.set_idle()
  5745. # self.ui.show()
  5746. def on_toggle_code_editor(self):
  5747. self.defaults.report_usage("on_toggle_code_editor()")
  5748. if self.toggle_codeeditor is False:
  5749. self.init_code_editor(name=_("Code Editor"))
  5750. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5751. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5752. self.text_editor_tab.buttonSave.clicked.disconnect()
  5753. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5754. else:
  5755. for idx in range(self.ui.plot_tab_area.count()):
  5756. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5757. self.ui.plot_tab_area.closeTab(idx)
  5758. break
  5759. self.toggle_codeeditor = False
  5760. def on_code_editor_close(self):
  5761. self.toggle_codeeditor = False
  5762. def goto_text_line(self):
  5763. """
  5764. Will scroll a text to the specified text line.
  5765. :return: None
  5766. """
  5767. dia_box = Dialog_box(title=_("Go to Line ..."),
  5768. label=_("Line:"),
  5769. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5770. initial_text='')
  5771. try:
  5772. line = int(dia_box.location) - 1
  5773. except (ValueError, TypeError):
  5774. line = 0
  5775. if dia_box.ok:
  5776. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5777. # at the top of the window
  5778. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5779. # get the document() of the AppTextEditor
  5780. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5781. # create a Text Cursor based on the searched line
  5782. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5783. # set cursor of the code editor with the cursor at the searcehd line
  5784. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5785. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5786. """
  5787. Re-generates all plots from all objects.
  5788. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5789. :param muted: if True don't print messages
  5790. :param use_thread: if True will use threading for plotting the objects
  5791. :return: None
  5792. """
  5793. self.log.debug("Plot_all()")
  5794. if muted is not True:
  5795. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5796. for plot_obj in self.collection.get_list():
  5797. def worker_task(obj):
  5798. with self.proc_container.new("Plotting"):
  5799. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5800. if fit_view is True:
  5801. self.app_obj.object_plotted.emit(obj)
  5802. if use_thread is True:
  5803. # Send to worker
  5804. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5805. else:
  5806. worker_task(plot_obj)
  5807. def register_folder(self, filename):
  5808. """
  5809. Register the last folder used by the app to open something
  5810. :param filename: the last folder is extracted from the filename
  5811. :return: None
  5812. """
  5813. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5814. def register_save_folder(self, filename):
  5815. """
  5816. Register the last folder used by the app to save something
  5817. :param filename: the last folder is extracted from the filename
  5818. :return: None
  5819. """
  5820. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5821. # def set_progress_bar(self, percentage, text=""):
  5822. # """
  5823. # Set a progress bar to a value (percentage)
  5824. #
  5825. # :param percentage: Value set to the progressbar
  5826. # :param text: Not used
  5827. # :return: None
  5828. # """
  5829. # self.ui.progress_bar.setValue(int(percentage))
  5830. def setup_recent_items(self):
  5831. """
  5832. Setup a dictionary with the recent files accessed, organized by type
  5833. :return:
  5834. """
  5835. icons = {
  5836. "gerber": self.resource_location + "/flatcam_icon16.png",
  5837. "excellon": self.resource_location + "/drill16.png",
  5838. 'geometry': self.resource_location + "/geometry16.png",
  5839. "cncjob": self.resource_location + "/cnc16.png",
  5840. "script": self.resource_location + "/script_new24.png",
  5841. "document": self.resource_location + "/notes16_1.png",
  5842. "project": self.resource_location + "/project16.png",
  5843. "svg": self.resource_location + "/geometry16.png",
  5844. "dxf": self.resource_location + "/dxf16.png",
  5845. "pdf": self.resource_location + "/pdf32.png",
  5846. "image": self.resource_location + "/image16.png"
  5847. }
  5848. try:
  5849. image_opener = self.image_tool.import_image
  5850. except AttributeError:
  5851. image_opener = None
  5852. openers = {
  5853. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5854. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5855. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5856. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5857. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5858. "document": None,
  5859. 'project': self.f_handlers.open_project,
  5860. 'svg': self.f_handlers.import_svg,
  5861. 'dxf': self.f_handlers.import_dxf,
  5862. 'image': image_opener,
  5863. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5864. }
  5865. # Open recent file for files
  5866. try:
  5867. f = open(self.data_path + '/recent.json')
  5868. except IOError:
  5869. App.log.error("Failed to load recent item list.")
  5870. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5871. return
  5872. try:
  5873. self.recent = json.load(f)
  5874. except json.errors.JSONDecodeError:
  5875. App.log.error("Failed to parse recent item list.")
  5876. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5877. f.close()
  5878. return
  5879. f.close()
  5880. # Open recent file for projects
  5881. try:
  5882. fp = open(self.data_path + '/recent_projects.json')
  5883. except IOError:
  5884. App.log.error("Failed to load recent project item list.")
  5885. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5886. return
  5887. try:
  5888. self.recent_projects = json.load(fp)
  5889. except json.errors.JSONDecodeError:
  5890. App.log.error("Failed to parse recent project item list.")
  5891. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5892. fp.close()
  5893. return
  5894. fp.close()
  5895. # Closure needed to create callbacks in a loop.
  5896. # Otherwise late binding occurs.
  5897. def make_callback(func, fname):
  5898. def opener():
  5899. func(fname)
  5900. return opener
  5901. def reset_recent_files():
  5902. # Reset menu
  5903. self.ui.recent.clear()
  5904. self.recent = []
  5905. try:
  5906. ff = open(self.data_path + '/recent.json', 'w')
  5907. except IOError:
  5908. App.log.error("Failed to open recent items file for writing.")
  5909. return
  5910. json.dump(self.recent, ff)
  5911. def reset_recent_projects():
  5912. # Reset menu
  5913. self.ui.recent_projects.clear()
  5914. self.recent_projects = []
  5915. try:
  5916. frp = open(self.data_path + '/recent_projects.json', 'w')
  5917. except IOError:
  5918. App.log.error("Failed to open recent projects items file for writing.")
  5919. return
  5920. json.dump(self.recent, frp)
  5921. # Reset menu
  5922. self.ui.recent.clear()
  5923. self.ui.recent_projects.clear()
  5924. # Create menu items for projects
  5925. for recent in self.recent_projects:
  5926. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5927. if recent['kind'] == 'project':
  5928. try:
  5929. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5930. # Attach callback
  5931. o = make_callback(openers[recent["kind"]], recent['filename'])
  5932. action.triggered.connect(o)
  5933. self.ui.recent_projects.addAction(action)
  5934. except KeyError:
  5935. App.log.error("Unsupported file type: %s" % recent["kind"])
  5936. # Last action in Recent Files menu is one that Clear the content
  5937. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5938. (_("Clear Recent projects")), self)
  5939. clear_action_proj.triggered.connect(reset_recent_projects)
  5940. self.ui.recent_projects.addSeparator()
  5941. self.ui.recent_projects.addAction(clear_action_proj)
  5942. # Create menu items for files
  5943. for recent in self.recent:
  5944. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5945. if recent['kind'] != 'project':
  5946. try:
  5947. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5948. # Attach callback
  5949. o = make_callback(openers[recent["kind"]], recent['filename'])
  5950. action.triggered.connect(o)
  5951. self.ui.recent.addAction(action)
  5952. except KeyError:
  5953. App.log.error("Unsupported file type: %s" % recent["kind"])
  5954. # Last action in Recent Files menu is one that Clear the content
  5955. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5956. (_("Clear Recent files")), self)
  5957. clear_action.triggered.connect(reset_recent_files)
  5958. self.ui.recent.addSeparator()
  5959. self.ui.recent.addAction(clear_action)
  5960. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5961. # self.ui.menufilerecent.set_submenu(recent_menu)
  5962. # recent_menu.show_all()
  5963. # self.ui.recent.show()
  5964. self.log.debug("Recent items list has been populated.")
  5965. def on_properties_tab_click(self, index):
  5966. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  5967. self.setup_default_properties_tab()
  5968. def setup_default_properties_tab(self):
  5969. """
  5970. Default text for the Properties tab when is not taken by the Object UI.
  5971. :return:
  5972. """
  5973. # label = QtWidgets.QLabel("Choose an item from Project")
  5974. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5975. # sel_title = QtWidgets.QTextEdit()
  5976. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5977. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5978. #
  5979. # f_settings = QSettings("Open Source", "FlatCAM")
  5980. # if f_settings.contains("notebook_font_size"):
  5981. # fsize = f_settings.value('notebook_font_size', type=int)
  5982. # else:
  5983. # fsize = 12
  5984. #
  5985. # tsize = fsize + int(fsize / 2)
  5986. #
  5987. # selected_text = ''
  5988. #
  5989. # sel_title.setText(selected_text)
  5990. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5991. # Tree Widget
  5992. d_properties_tw = FCTree(columns=2)
  5993. d_properties_tw.setObjectName("default_properties")
  5994. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5995. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  5996. root = d_properties_tw.invisibleRootItem()
  5997. font = QtGui.QFont()
  5998. font.setBold(True)
  5999. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6000. # main Items categories
  6001. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6002. d_properties_tw.addChild(parent=general_cat,
  6003. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6004. d_properties_tw.addChild(parent=general_cat,
  6005. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6006. d_properties_tw.addChild(parent=general_cat,
  6007. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6008. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6009. d_properties_tw.addChild(parent=grid_cat,
  6010. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6011. column1=True)
  6012. d_properties_tw.addChild(parent=grid_cat,
  6013. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6014. column1=True)
  6015. d_properties_tw.addChild(parent=grid_cat,
  6016. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6017. column1=True)
  6018. d_properties_tw.addChild(parent=grid_cat,
  6019. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6020. column1=True)
  6021. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6022. d_properties_tw.addChild(parent=canvas_cat,
  6023. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6024. column1=True)
  6025. d_properties_tw.addChild(parent=canvas_cat,
  6026. title=['%s:' % _("Workspace active"),
  6027. '%s' % str(self.defaults['global_workspace'])],
  6028. column1=True)
  6029. d_properties_tw.addChild(parent=canvas_cat,
  6030. title=['%s:' % _("Workspace size"),
  6031. '%s' % str(self.defaults['global_workspaceT'])],
  6032. column1=True)
  6033. d_properties_tw.addChild(parent=canvas_cat,
  6034. title=['%s:' % _("Workspace orientation"),
  6035. '%s' % _("Portrait") if self.defaults[
  6036. 'global_workspace_orientation'] == 'p' else
  6037. _("Landscape")],
  6038. column1=True)
  6039. d_properties_tw.addChild(parent=canvas_cat,
  6040. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6041. column1=True)
  6042. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6043. def setup_obj_classes(self):
  6044. """
  6045. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6046. class.
  6047. :return: None
  6048. """
  6049. FlatCAMObj.app = self
  6050. ObjectCollection.app = self
  6051. Gerber.app = self
  6052. Excellon.app = self
  6053. Geometry.app = self
  6054. CNCjob.app = self
  6055. FCProcess.app = self
  6056. FCProcessContainer.app = self
  6057. OptionsGroupUI.app = self
  6058. def version_check(self):
  6059. """
  6060. Checks for the latest version of the program. Alerts the
  6061. user if theirs is outdated. This method is meant to be run
  6062. in a separate thread.
  6063. :return: None
  6064. """
  6065. self.log.debug("version_check()")
  6066. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6067. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6068. App.version_url,
  6069. str(self.defaults['global_serial']),
  6070. str(self.version),
  6071. str(self.os),
  6072. urllib.parse.urlencode(self.defaults["global_stats"])
  6073. )
  6074. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6075. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6076. # urllib.parse.urlencode(self.defaults["global_stats"])
  6077. else:
  6078. # no_stats dict; just so it won't break things on website
  6079. no_ststs_dict = {}
  6080. no_ststs_dict["global_ststs"] = {}
  6081. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6082. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6083. App.log.debug("Checking for updates @ %s" % full_url)
  6084. # ## Get the data
  6085. try:
  6086. f = urllib.request.urlopen(full_url)
  6087. except Exception:
  6088. # App.log.warning("Failed checking for latest version. Could not connect.")
  6089. self.log.warning("Failed checking for latest version. Could not connect.")
  6090. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6091. return
  6092. try:
  6093. data = json.load(f)
  6094. except Exception as e:
  6095. App.log.error("Could not parse information about latest version.")
  6096. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6097. App.log.debug("json.load(): %s" % str(e))
  6098. f.close()
  6099. return
  6100. f.close()
  6101. # ## Latest version?
  6102. if self.version >= data["version"]:
  6103. App.log.debug("FlatCAM is up to date!")
  6104. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6105. return
  6106. App.log.debug("Newer version available.")
  6107. self.message.emit(
  6108. _("Newer Version Available"),
  6109. '%s<br><br>><b>%s</b><br>%s' % (
  6110. _("There is a newer version of FlatCAM available for download:"),
  6111. str(data["name"]),
  6112. str(data["message"])
  6113. ),
  6114. _("info")
  6115. )
  6116. def on_plotcanvas_setup(self, container=None):
  6117. """
  6118. This is doing the setup for the plot area (canvas).
  6119. :param container: QT Widget where to install the canvas
  6120. :return: None
  6121. """
  6122. if container:
  6123. plot_container = container
  6124. else:
  6125. plot_container = self.ui.right_layout
  6126. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6127. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6128. self.is_legacy = True
  6129. self.defaults["global_graphic_engine"] = "2D"
  6130. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6131. else:
  6132. try:
  6133. self.plotcanvas = PlotCanvas(plot_container, self)
  6134. except Exception as er:
  6135. msg_txt = traceback.format_exc()
  6136. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6137. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6138. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6139. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6140. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6141. msg += msg_txt
  6142. self.inform.emit(msg)
  6143. return 'fail'
  6144. # So it can receive key presses
  6145. self.plotcanvas.native.setFocus()
  6146. if self.is_legacy is False:
  6147. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6148. # Set the mouse button for panning
  6149. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6150. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6151. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6152. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6153. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6154. # Keys over plot enabled
  6155. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6156. if self.defaults['global_cursor_type'] == 'small':
  6157. self.app_cursor = self.plotcanvas.new_cursor()
  6158. else:
  6159. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6160. if self.ui.grid_snap_btn.isChecked():
  6161. self.app_cursor.enabled = True
  6162. else:
  6163. self.app_cursor.enabled = False
  6164. if self.is_legacy is False:
  6165. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6166. else:
  6167. # will use the default Matplotlib axes
  6168. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6169. def on_zoom_fit(self):
  6170. """
  6171. Callback for zoom-fit request. This can be either from the corresponding
  6172. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6173. with axes limits from the geometry bounds of all objects.
  6174. :return: None
  6175. """
  6176. if self.is_legacy is False:
  6177. self.plotcanvas.fit_view()
  6178. else:
  6179. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6180. width = xmax - xmin
  6181. height = ymax - ymin
  6182. xmin -= 0.05 * width
  6183. xmax += 0.05 * width
  6184. ymin -= 0.05 * height
  6185. ymax += 0.05 * height
  6186. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6187. def on_zoom_in(self):
  6188. """
  6189. Callback for zoom-in request.
  6190. :return:
  6191. """
  6192. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6193. def on_zoom_out(self):
  6194. """
  6195. Callback for zoom-out request.
  6196. :return:
  6197. """
  6198. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6199. def disable_all_plots(self):
  6200. self.defaults.report_usage("disable_all_plots()")
  6201. self.disable_plots(self.collection.get_list())
  6202. self.inform.emit('[success] %s' % _("All plots disabled."))
  6203. def disable_other_plots(self):
  6204. self.defaults.report_usage("disable_other_plots()")
  6205. self.disable_plots(self.collection.get_non_selected())
  6206. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6207. def enable_all_plots(self):
  6208. self.defaults.report_usage("enable_all_plots()")
  6209. self.enable_plots(self.collection.get_list())
  6210. self.inform.emit('[success] %s' % _("All plots enabled."))
  6211. def enable_other_plots(self):
  6212. self.defaults.report_usage("enable_other_plots()")
  6213. self.enable_plots(self.collection.get_non_selected())
  6214. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6215. def on_enable_sel_plots(self):
  6216. log.debug("App.on_enable_sel_plot()")
  6217. object_list = self.collection.get_selected()
  6218. self.enable_plots(objects=object_list)
  6219. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6220. def on_disable_sel_plots(self):
  6221. log.debug("App.on_disable_sel_plot()")
  6222. # self.inform.emit(_("Disabling plots ..."))
  6223. object_list = self.collection.get_selected()
  6224. self.disable_plots(objects=object_list)
  6225. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6226. def enable_plots(self, objects):
  6227. """
  6228. Enable plots
  6229. :param objects: list of Objects to be enabled
  6230. :return:
  6231. """
  6232. log.debug("Enabling plots ...")
  6233. # self.inform.emit(_("Working ..."))
  6234. for obj in objects:
  6235. if obj.options['plot'] is False:
  6236. obj.options.set_change_callback(lambda x: None)
  6237. obj.options['plot'] = True
  6238. try:
  6239. # only the Gerber obj has on_plot_cb_click() method
  6240. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6241. # disable this cb while disconnected,
  6242. # in case the operation takes time the user is not allowed to change it
  6243. obj.ui.plot_cb.setDisabled(True)
  6244. except AttributeError:
  6245. pass
  6246. obj.set_form_item("plot")
  6247. try:
  6248. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6249. obj.ui.plot_cb.setDisabled(False)
  6250. except AttributeError:
  6251. pass
  6252. obj.options.set_change_callback(obj.on_options_change)
  6253. self.collection.update_view()
  6254. def worker_task(objs):
  6255. with self.proc_container.new(_("Enabling plots ...")):
  6256. for plot_obj in objs:
  6257. # obj.options['plot'] = True
  6258. if isinstance(plot_obj, CNCJobObject):
  6259. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6260. else:
  6261. plot_obj.plot(visible=True)
  6262. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6263. def disable_plots(self, objects):
  6264. """
  6265. Disables plots
  6266. :param objects: list of Objects to be disabled
  6267. :return:
  6268. """
  6269. log.debug("Disabling plots ...")
  6270. # self.inform.emit(_("Working ..."))
  6271. for obj in objects:
  6272. if obj.options['plot'] is True:
  6273. obj.options.set_change_callback(lambda x: None)
  6274. obj.options['plot'] = False
  6275. try:
  6276. # only the Gerber obj has on_plot_cb_click() method
  6277. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6278. obj.ui.plot_cb.setDisabled(True)
  6279. except AttributeError:
  6280. pass
  6281. obj.set_form_item("plot")
  6282. try:
  6283. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6284. obj.ui.plot_cb.setDisabled(False)
  6285. except AttributeError:
  6286. pass
  6287. obj.options.set_change_callback(obj.on_options_change)
  6288. try:
  6289. self.delete_selection_shape()
  6290. except Exception as e:
  6291. log.debug("App.disable_plots() --> %s" % str(e))
  6292. self.collection.update_view()
  6293. def worker_task(objs):
  6294. with self.proc_container.new(_("Disabling plots ...")):
  6295. for plot_obj in objs:
  6296. # obj.options['plot'] = True
  6297. if isinstance(plot_obj, CNCJobObject):
  6298. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6299. else:
  6300. plot_obj.plot(visible=False)
  6301. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6302. def toggle_plots(self, objects):
  6303. """
  6304. Toggle plots visibility
  6305. :param objects: list of Objects for which to be toggled the visibility
  6306. :return: None
  6307. """
  6308. # if no objects selected then do nothing
  6309. if not self.collection.get_selected():
  6310. return
  6311. log.debug("Toggling plots ...")
  6312. self.inform.emit(_("Working ..."))
  6313. for obj in objects:
  6314. if obj.options['plot'] is False:
  6315. obj.options['plot'] = True
  6316. else:
  6317. obj.options['plot'] = False
  6318. self.app_obj.plots_updated.emit()
  6319. def clear_plots(self):
  6320. """
  6321. Clear the plots
  6322. :return: None
  6323. """
  6324. objects = self.collection.get_list()
  6325. for obj in objects:
  6326. obj.clear(obj == objects[-1])
  6327. # Clear pool to free memory
  6328. self.clear_pool()
  6329. def on_set_color_action_triggered(self):
  6330. """
  6331. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6332. :return:
  6333. """
  6334. new_color = self.defaults['gerber_plot_fill']
  6335. clicked_action = self.sender()
  6336. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6337. act_name = clicked_action.text()
  6338. sel_obj_list = self.collection.get_selected()
  6339. if not sel_obj_list:
  6340. return
  6341. # a default value, I just chose this one
  6342. alpha_level = 'BF'
  6343. for sel_obj in sel_obj_list:
  6344. if sel_obj.kind == 'excellon':
  6345. alpha_level = str(hex(
  6346. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6347. elif sel_obj.kind == 'gerber':
  6348. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6349. elif sel_obj.kind == 'geometry':
  6350. alpha_level = 'FF'
  6351. else:
  6352. log.debug(
  6353. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6354. continue
  6355. sel_obj.alpha_level = alpha_level
  6356. if act_name == _('Red'):
  6357. new_color = '#FF0000' + alpha_level
  6358. if act_name == _('Blue'):
  6359. new_color = '#0000FF' + alpha_level
  6360. if act_name == _('Yellow'):
  6361. new_color = '#FFDF00' + alpha_level
  6362. if act_name == _('Green'):
  6363. new_color = '#00FF00' + alpha_level
  6364. if act_name == _('Purple'):
  6365. new_color = '#FF00FF' + alpha_level
  6366. if act_name == _('Brown'):
  6367. new_color = '#A52A2A' + alpha_level
  6368. if act_name == _('White'):
  6369. new_color = '#FFFFFF' + alpha_level
  6370. if act_name == _('Black'):
  6371. new_color = '#000000' + alpha_level
  6372. if act_name == _('Custom'):
  6373. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6374. c_dialog = QtWidgets.QColorDialog()
  6375. plot_fill_color = c_dialog.getColor(initial=new_color)
  6376. if plot_fill_color.isValid() is False:
  6377. return
  6378. new_color = str(plot_fill_color.name()) + alpha_level
  6379. if act_name == _("Default"):
  6380. for sel_obj in sel_obj_list:
  6381. if sel_obj.kind == 'excellon':
  6382. new_color = self.defaults['excellon_plot_fill']
  6383. new_line_color = self.defaults['excellon_plot_line']
  6384. elif sel_obj.kind == 'gerber':
  6385. new_color = self.defaults['gerber_plot_fill']
  6386. new_line_color = self.defaults['gerber_plot_line']
  6387. elif sel_obj.kind == 'geometry':
  6388. new_color = self.defaults['geometry_plot_line']
  6389. new_line_color = self.defaults['geometry_plot_line']
  6390. else:
  6391. log.debug(
  6392. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6393. continue
  6394. sel_obj.fill_color = new_color
  6395. sel_obj.outline_color = new_line_color
  6396. sel_obj.shapes.redraw(
  6397. update_colors=(new_color, new_line_color)
  6398. )
  6399. return
  6400. if act_name == _("Opacity"):
  6401. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6402. # '%s:' % _("Value"),
  6403. # min=0, max=255, step=1, value=191)
  6404. alpha_dialog = FCInputDialogSlider(
  6405. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6406. alpha_level, ok_button = alpha_dialog.get_results()
  6407. if ok_button:
  6408. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6409. for sel_obj in sel_obj_list:
  6410. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6411. sel_obj.shapes.redraw(
  6412. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6413. )
  6414. return
  6415. new_line_color = color_variant(new_color[:7], 0.7)
  6416. if act_name == _("White"):
  6417. new_line_color = color_variant("#dedede", 0.7)
  6418. for sel_obj in sel_obj_list:
  6419. sel_obj.fill_color = new_color
  6420. sel_obj.outline_color = new_line_color
  6421. sel_obj.shapes.redraw(
  6422. update_colors=(new_color, new_line_color)
  6423. )
  6424. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6425. group = self.collection.group_items["gerber"]
  6426. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6427. new_c = (new_line_color, new_color)
  6428. for sel_obj in sel_obj_list:
  6429. if sel_obj.kind == 'gerber':
  6430. item = sel_obj.item
  6431. item_index = self.collection.index(item.row(), 0, group_index)
  6432. idx = item_index.row()
  6433. self.defaults["gerber_color_list"][idx] = new_c
  6434. def generate_cnc_job(self, objects):
  6435. """
  6436. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6437. :param objects: Selected objects in the Project Tab
  6438. :return:
  6439. """
  6440. self.defaults.report_usage("generate_cnc_job()")
  6441. # for obj in objects:
  6442. # obj.generatecncjob()
  6443. for obj in objects:
  6444. obj.on_generatecnc_button_click()
  6445. def start_delayed_quit(self, delay, filename, should_quit=None):
  6446. """
  6447. :param delay: period of checking if project file size is more than zero; in seconds
  6448. :param filename: the name of the project file to be checked periodically for size more than zero
  6449. :param should_quit: if the task finished will be followed by an app quit; boolean
  6450. :return:
  6451. """
  6452. to_quit = should_quit
  6453. self.save_timer = QtCore.QTimer()
  6454. self.save_timer.setInterval(delay)
  6455. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6456. self.save_timer.start()
  6457. def check_project_file_size(self, filename, should_quit=None):
  6458. """
  6459. :param filename: the name of the project file to be checked periodically for size more than zero
  6460. :param should_quit: will quit the app if True; boolean
  6461. :return:
  6462. """
  6463. try:
  6464. if os.stat(filename).st_size > 0:
  6465. self.save_in_progress = False
  6466. self.save_timer.stop()
  6467. if should_quit:
  6468. self.app_quit.emit()
  6469. except Exception:
  6470. traceback.print_exc()
  6471. def save_project_auto(self):
  6472. """
  6473. Called periodically to save the project.
  6474. 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
  6475. # progress.
  6476. :return:
  6477. """
  6478. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6479. self.on_file_saveproject()
  6480. def save_project_auto_update(self):
  6481. """
  6482. Update the auto save time interval value.
  6483. :return:
  6484. """
  6485. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6486. try:
  6487. if self.autosave_timer.isActive():
  6488. self.autosave_timer.stop()
  6489. except Exception:
  6490. pass
  6491. if self.defaults['global_autosave'] is True:
  6492. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6493. self.autosave_timer.start()
  6494. def on_options_app2project(self):
  6495. """
  6496. Callback for Options->Transfer Options->App=>Project. Copies options
  6497. from application defaults to project defaults.
  6498. :return: None
  6499. """
  6500. self.defaults.report_usage("on_options_app2project")
  6501. self.preferencesUiManager.defaults_read_form()
  6502. self.options.update(self.defaults)
  6503. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6504. """
  6505. Shows a message on the FlatCAM Shell
  6506. :param msg: Message to display.
  6507. :param show: Opens the shell.
  6508. :param error: Shows the message as an error.
  6509. :param warning: Shows the message as an warning.
  6510. :param success: Shows the message as an success.
  6511. :param selected: Indicate that something was selected on canvas
  6512. :return: None
  6513. """
  6514. end = '\n' if new_line is True else ''
  6515. if show:
  6516. self.ui.shell_dock.show()
  6517. try:
  6518. if error:
  6519. self.shell.append_error(msg + end)
  6520. elif warning:
  6521. self.shell.append_warning(msg + end)
  6522. elif success:
  6523. self.shell.append_success(msg + end)
  6524. elif selected:
  6525. self.shell.append_selected(msg + end)
  6526. else:
  6527. self.shell.append_output(msg + end)
  6528. except AttributeError:
  6529. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6530. def dec_format(self, val, dec=None):
  6531. """
  6532. Returns a formatted float value with a certain number of decimals
  6533. """
  6534. dec_nr = dec if dec is not None else self.decimals
  6535. return float('%.*f' % (dec_nr, val))
  6536. class ArgsThread(QtCore.QObject):
  6537. open_signal = pyqtSignal(list)
  6538. start = pyqtSignal()
  6539. stop = pyqtSignal()
  6540. if sys.platform == 'win32':
  6541. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6542. else:
  6543. address = ('/tmp/testipc', 'AF_UNIX')
  6544. def __init__(self):
  6545. super().__init__()
  6546. self.listener = None
  6547. self.thread_exit = False
  6548. self.start.connect(self.run)
  6549. self.stop.connect(self.close_listener)
  6550. def my_loop(self, address):
  6551. try:
  6552. self.listener = Listener(*address)
  6553. while self.thread_exit is False:
  6554. conn = self.listener.accept()
  6555. self.serve(conn)
  6556. except socket.error:
  6557. try:
  6558. conn = Client(*address)
  6559. conn.send(sys.argv)
  6560. conn.send('close')
  6561. # close the current instance only if there are args
  6562. if len(sys.argv) > 1:
  6563. try:
  6564. self.listener.close()
  6565. except Exception:
  6566. pass
  6567. sys.exit()
  6568. except ConnectionRefusedError:
  6569. if sys.platform == 'win32':
  6570. pass
  6571. else:
  6572. os.system('rm /tmp/testipc')
  6573. self.listener = Listener(*address)
  6574. while True:
  6575. conn = self.listener.accept()
  6576. self.serve(conn)
  6577. def serve(self, conn):
  6578. while self.thread_exit is False:
  6579. msg = conn.recv()
  6580. if msg == 'close':
  6581. break
  6582. self.open_signal.emit(msg)
  6583. conn.close()
  6584. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6585. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6586. @pyqtSlot()
  6587. def run(self):
  6588. self.my_loop(self.address)
  6589. @pyqtSlot()
  6590. def close_listener(self):
  6591. self.thread_exit = True
  6592. self.listener.close()
  6593. class MenuFileHandlers(QtCore.QObject):
  6594. def __init__(self, app):
  6595. super().__init__()
  6596. self.app = app
  6597. self.inform = self.app.inform
  6598. self.splash = self.app.splash
  6599. self.worker_task = self.app.worker_task
  6600. self.defaults = self.app.defaults
  6601. self.pagesize = {}
  6602. def on_fileopengerber(self, signal, name=None):
  6603. """
  6604. File menu callback for opening a Gerber.
  6605. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6606. :param name:
  6607. :return: None
  6608. """
  6609. self.app.log.debug("on_fileopengerber()")
  6610. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6611. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6612. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6613. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6614. "*.outline);;" \
  6615. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6616. "*.mil);;" \
  6617. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6618. "Allegro Files (*.art);;" \
  6619. "Mentor Files (*.pho *.gdo);;" \
  6620. "All Files (*.*)"
  6621. if name is None:
  6622. try:
  6623. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6624. directory=self.app.get_last_folder(),
  6625. filter=_filter_,
  6626. initialFilter=self.app.last_op_gerber_filter)
  6627. except TypeError:
  6628. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6629. filenames = [str(filename) for filename in filenames]
  6630. self.app.last_op_gerber_filter = _f
  6631. else:
  6632. filenames = [name]
  6633. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6634. "Canvas initialization finished in"),
  6635. '%.2f' % self.app.used_time,
  6636. _("Opening Gerber file.")),
  6637. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6638. color=QtGui.QColor("gray"))
  6639. if len(filenames) == 0:
  6640. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6641. else:
  6642. for filename in filenames:
  6643. if filename != '':
  6644. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6645. def on_fileopenexcellon(self, signal, name=None):
  6646. """
  6647. File menu callback for opening an Excellon file.
  6648. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6649. :param name:
  6650. :return: None
  6651. """
  6652. self.app.log.debug("on_fileopenexcellon()")
  6653. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6654. "All Files (*.*)"
  6655. if name is None:
  6656. try:
  6657. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6658. directory=self.app.get_last_folder(),
  6659. filter=_filter_,
  6660. initialFilter=self.app.last_op_excellon_filter)
  6661. except TypeError:
  6662. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6663. filenames = [str(filename) for filename in filenames]
  6664. self.app.last_op_excellon_filter = _f
  6665. else:
  6666. filenames = [str(name)]
  6667. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6668. "Canvas initialization finished in"),
  6669. '%.2f' % self.app.used_time,
  6670. _("Opening Excellon file.")),
  6671. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6672. color=QtGui.QColor("gray"))
  6673. if len(filenames) == 0:
  6674. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6675. else:
  6676. for filename in filenames:
  6677. if filename != '':
  6678. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6679. def on_fileopengcode(self, signal, name=None):
  6680. """
  6681. File menu call back for opening gcode.
  6682. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6683. :param name:
  6684. :return:
  6685. """
  6686. self.app.log.debug("on_fileopengcode()")
  6687. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6688. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6689. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6690. "All Files (*.*)"
  6691. if name is None:
  6692. try:
  6693. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6694. directory=self.app.get_last_folder(),
  6695. filter=_filter_,
  6696. initialFilter=self.app.last_op_gcode_filter)
  6697. except TypeError:
  6698. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6699. filenames = [str(filename) for filename in filenames]
  6700. self.app.last_op_gcode_filter = _f
  6701. else:
  6702. filenames = [name]
  6703. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6704. "Canvas initialization finished in"),
  6705. '%.2f' % self.app.used_time,
  6706. _("Opening G-Code file.")),
  6707. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6708. color=QtGui.QColor("gray"))
  6709. if len(filenames) == 0:
  6710. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6711. else:
  6712. for filename in filenames:
  6713. if filename != '':
  6714. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6715. def on_file_openproject(self, signal):
  6716. """
  6717. File menu callback for opening a project.
  6718. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6719. :return: None
  6720. """
  6721. self.app.log.debug("on_file_openproject()")
  6722. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6723. try:
  6724. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6725. directory=self.app.get_last_folder(), filter=_filter_)
  6726. except TypeError:
  6727. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6728. filename = str(filename)
  6729. if filename == "":
  6730. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6731. else:
  6732. # self.worker_task.emit({'fcn': self.open_project,
  6733. # 'params': [filename]})
  6734. # The above was failing because open_project() is not
  6735. # thread safe. The new_project()
  6736. self.open_project(filename)
  6737. def on_fileopenhpgl2(self, signal, name=None):
  6738. """
  6739. File menu callback for opening a HPGL2.
  6740. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6741. :param name:
  6742. :return: None
  6743. """
  6744. self.app.log.debug("on_fileopenhpgl2()")
  6745. _filter_ = "HPGL2 Files (*.plt);;" \
  6746. "All Files (*.*)"
  6747. if name is None:
  6748. try:
  6749. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6750. directory=self.app.get_last_folder(),
  6751. filter=_filter_)
  6752. except TypeError:
  6753. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6754. filenames = [str(filename) for filename in filenames]
  6755. else:
  6756. filenames = [name]
  6757. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6758. "Canvas initialization finished in"),
  6759. '%.2f' % self.app.used_time,
  6760. _("Opening HPGL2 file.")),
  6761. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6762. color=QtGui.QColor("gray"))
  6763. if len(filenames) == 0:
  6764. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6765. else:
  6766. for filename in filenames:
  6767. if filename != '':
  6768. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6769. def on_file_openconfig(self, signal):
  6770. """
  6771. File menu callback for opening a config file.
  6772. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6773. :return: None
  6774. """
  6775. self.app.log.debug("on_file_openconfig()")
  6776. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6777. try:
  6778. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6779. directory=self.app.data_path, filter=_filter_)
  6780. except TypeError:
  6781. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6782. filter=_filter_)
  6783. if filename == "":
  6784. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6785. else:
  6786. self.open_config_file(filename)
  6787. def on_file_exportsvg(self):
  6788. """
  6789. Callback for menu item File->Export SVG.
  6790. :return: None
  6791. """
  6792. self.app.log.debug("on_file_exportsvg()")
  6793. obj = self.app.collection.get_active()
  6794. if obj is None:
  6795. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6796. msg = _("Please Select a Geometry object to export")
  6797. msgbox = QtWidgets.QMessageBox()
  6798. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6799. msgbox.setInformativeText(msg)
  6800. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6801. msgbox.setDefaultButton(bt_ok)
  6802. msgbox.exec_()
  6803. return
  6804. # Check for more compatible types and add as required
  6805. if (not isinstance(obj, GeometryObject)
  6806. and not isinstance(obj, GerberObject)
  6807. and not isinstance(obj, CNCJobObject)
  6808. and not isinstance(obj, ExcellonObject)):
  6809. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6810. msgbox = QtWidgets.QMessageBox()
  6811. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6812. msgbox.setInformativeText(msg)
  6813. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6814. msgbox.setDefaultButton(bt_ok)
  6815. msgbox.exec_()
  6816. return
  6817. name = obj.options["name"]
  6818. _filter = "SVG File (*.svg);;All Files (*.*)"
  6819. try:
  6820. filename, _f = FCFileSaveDialog.get_saved_filename(
  6821. caption=_("Export SVG"),
  6822. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6823. ext_filter=_filter)
  6824. except TypeError:
  6825. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  6826. filename = str(filename)
  6827. if filename == "":
  6828. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6829. return
  6830. else:
  6831. self.export_svg(name, filename)
  6832. if self.defaults["global_open_style"] is False:
  6833. self.app.file_opened.emit("SVG", filename)
  6834. self.app.file_saved.emit("SVG", filename)
  6835. def on_file_exportpng(self):
  6836. self.app.log.debug("on_file_exportpng()")
  6837. date = str(datetime.today()).rpartition('.')[0]
  6838. date = ''.join(c for c in date if c not in ':-')
  6839. date = date.replace(' ', '_')
  6840. data = None
  6841. if self.app.is_legacy is False:
  6842. image = _screenshot(alpha=False)
  6843. data = np.asarray(image)
  6844. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6845. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6846. return
  6847. filter_ = "PNG File (*.png);;All Files (*.*)"
  6848. try:
  6849. filename, _f = FCFileSaveDialog.get_saved_filename(
  6850. caption=_("Export PNG Image"),
  6851. directory=self.app.get_last_save_folder() + '/png_' + date,
  6852. ext_filter=filter_)
  6853. except TypeError:
  6854. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  6855. filename = str(filename)
  6856. if filename == "":
  6857. self.inform.emit(_("Cancelled."))
  6858. return
  6859. else:
  6860. if self.app.is_legacy is False:
  6861. write_png(filename, data)
  6862. else:
  6863. self.app.plotcanvas.figure.savefig(filename)
  6864. if self.defaults["global_open_style"] is False:
  6865. self.app.file_opened.emit("png", filename)
  6866. self.app.file_saved.emit("png", filename)
  6867. def on_file_savegerber(self):
  6868. """
  6869. Callback for menu item in Project context menu.
  6870. :return: None
  6871. """
  6872. self.app.log.debug("on_file_savegerber()")
  6873. obj = self.app.collection.get_active()
  6874. if obj is None:
  6875. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6876. return
  6877. # Check for more compatible types and add as required
  6878. if not isinstance(obj, GerberObject):
  6879. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6880. return
  6881. name = self.app.collection.get_active().options["name"]
  6882. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6883. try:
  6884. filename, _f = FCFileSaveDialog.get_saved_filename(
  6885. caption="Save Gerber source file",
  6886. directory=self.app.get_last_save_folder() + '/' + name,
  6887. ext_filter=_filter)
  6888. except TypeError:
  6889. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  6890. filename = str(filename)
  6891. if filename == "":
  6892. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6893. return
  6894. else:
  6895. self.save_source_file(name, filename)
  6896. if self.defaults["global_open_style"] is False:
  6897. self.app.file_opened.emit("Gerber", filename)
  6898. self.app.file_saved.emit("Gerber", filename)
  6899. def on_file_savescript(self):
  6900. """
  6901. Callback for menu item in Project context menu.
  6902. :return: None
  6903. """
  6904. self.app.log.debug("on_file_savescript()")
  6905. obj = self.app.collection.get_active()
  6906. if obj is None:
  6907. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6908. return
  6909. # Check for more compatible types and add as required
  6910. if not isinstance(obj, ScriptObject):
  6911. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6912. return
  6913. name = self.app.collection.get_active().options["name"]
  6914. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6915. try:
  6916. filename, _f = FCFileSaveDialog.get_saved_filename(
  6917. caption="Save Script source file",
  6918. directory=self.app.get_last_save_folder() + '/' + name,
  6919. ext_filter=_filter)
  6920. except TypeError:
  6921. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6922. filename = str(filename)
  6923. if filename == "":
  6924. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6925. return
  6926. else:
  6927. self.save_source_file(name, filename)
  6928. if self.defaults["global_open_style"] is False:
  6929. self.app.file_opened.emit("Script", filename)
  6930. self.app.file_saved.emit("Script", filename)
  6931. def on_file_savedocument(self):
  6932. """
  6933. Callback for menu item in Project context menu.
  6934. :return: None
  6935. """
  6936. self.app.log.debug("on_file_savedocument()")
  6937. obj = self.app.collection.get_active()
  6938. if obj is None:
  6939. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6940. return
  6941. # Check for more compatible types and add as required
  6942. if not isinstance(obj, ScriptObject):
  6943. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6944. return
  6945. name = self.app.collection.get_active().options["name"]
  6946. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6947. try:
  6948. filename, _f = FCFileSaveDialog.get_saved_filename(
  6949. caption="Save Document source file",
  6950. directory=self.app.get_last_save_folder() + '/' + name,
  6951. ext_filter=_filter)
  6952. except TypeError:
  6953. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6954. ext_filter=_filter)
  6955. filename = str(filename)
  6956. if filename == "":
  6957. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6958. return
  6959. else:
  6960. self.save_source_file(name, filename)
  6961. if self.defaults["global_open_style"] is False:
  6962. self.app.file_opened.emit("Document", filename)
  6963. self.app.file_saved.emit("Document", filename)
  6964. def on_file_saveexcellon(self):
  6965. """
  6966. Callback for menu item in project context menu.
  6967. :return: None
  6968. """
  6969. self.app.log.debug("on_file_saveexcellon()")
  6970. obj = self.app.collection.get_active()
  6971. if obj is None:
  6972. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6973. return
  6974. # Check for more compatible types and add as required
  6975. if not isinstance(obj, ExcellonObject):
  6976. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6977. return
  6978. name = self.app.collection.get_active().options["name"]
  6979. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6980. try:
  6981. filename, _f = FCFileSaveDialog.get_saved_filename(
  6982. caption=_("Save Excellon source file"),
  6983. directory=self.app.get_last_save_folder() + '/' + name,
  6984. ext_filter=_filter)
  6985. except TypeError:
  6986. filename, _f = FCFileSaveDialog.get_saved_filename(
  6987. caption=_("Save Excellon source file"), ext_filter=_filter)
  6988. filename = str(filename)
  6989. if filename == "":
  6990. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6991. return
  6992. else:
  6993. self.save_source_file(name, filename)
  6994. if self.defaults["global_open_style"] is False:
  6995. self.app.file_opened.emit("Excellon", filename)
  6996. self.app.file_saved.emit("Excellon", filename)
  6997. def on_file_exportexcellon(self):
  6998. """
  6999. Callback for menu item File->Export->Excellon.
  7000. :return: None
  7001. """
  7002. self.app.log.debug("on_file_exportexcellon()")
  7003. obj = self.app.collection.get_active()
  7004. if obj is None:
  7005. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7006. return
  7007. # Check for more compatible types and add as required
  7008. if not isinstance(obj, ExcellonObject):
  7009. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7010. return
  7011. name = self.app.collection.get_active().options["name"]
  7012. _filter = self.defaults["excellon_save_filters"]
  7013. try:
  7014. filename, _f = FCFileSaveDialog.get_saved_filename(
  7015. caption=_("Export Excellon"),
  7016. directory=self.app.get_last_save_folder() + '/' + name,
  7017. ext_filter=_filter)
  7018. except TypeError:
  7019. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  7020. filename = str(filename)
  7021. if filename == "":
  7022. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7023. return
  7024. else:
  7025. used_extension = filename.rpartition('.')[2]
  7026. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7027. self.export_excellon(name, filename)
  7028. if self.defaults["global_open_style"] is False:
  7029. self.app.file_opened.emit("Excellon", filename)
  7030. self.app.file_saved.emit("Excellon", filename)
  7031. def on_file_exportgerber(self):
  7032. """
  7033. Callback for menu item File->Export->Gerber.
  7034. :return: None
  7035. """
  7036. App.log.debug("on_file_exportgerber()")
  7037. obj = self.app.collection.get_active()
  7038. if obj is None:
  7039. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7040. return
  7041. # Check for more compatible types and add as required
  7042. if not isinstance(obj, GerberObject):
  7043. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7044. return
  7045. name = self.app.collection.get_active().options["name"]
  7046. _filter_ = self.defaults['gerber_save_filters']
  7047. try:
  7048. filename, _f = FCFileSaveDialog.get_saved_filename(
  7049. caption=_("Export Gerber"),
  7050. directory=self.app.get_last_save_folder() + '/' + name,
  7051. ext_filter=_filter_)
  7052. except TypeError:
  7053. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  7054. filename = str(filename)
  7055. if filename == "":
  7056. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7057. return
  7058. else:
  7059. used_extension = filename.rpartition('.')[2]
  7060. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7061. self.export_gerber(name, filename)
  7062. if self.defaults["global_open_style"] is False:
  7063. self.app.file_opened.emit("Gerber", filename)
  7064. self.app.file_saved.emit("Gerber", filename)
  7065. def on_file_exportdxf(self):
  7066. """
  7067. Callback for menu item File->Export DXF.
  7068. :return: None
  7069. """
  7070. App.log.debug("on_file_exportdxf()")
  7071. obj = self.app.collection.get_active()
  7072. if obj is None:
  7073. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7074. msg = _("Please Select a Geometry object to export")
  7075. msgbox = QtWidgets.QMessageBox()
  7076. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7077. msgbox.setInformativeText(msg)
  7078. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7079. msgbox.setDefaultButton(bt_ok)
  7080. msgbox.exec_()
  7081. return
  7082. # Check for more compatible types and add as required
  7083. if not isinstance(obj, GeometryObject):
  7084. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7085. msgbox = QtWidgets.QMessageBox()
  7086. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7087. msgbox.setInformativeText(msg)
  7088. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7089. msgbox.setDefaultButton(bt_ok)
  7090. msgbox.exec_()
  7091. return
  7092. name = self.app.collection.get_active().options["name"]
  7093. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7094. try:
  7095. filename, _f = FCFileSaveDialog.get_saved_filename(
  7096. caption=_("Export DXF"),
  7097. directory=self.app.get_last_save_folder() + '/' + name,
  7098. ext_filter=_filter_)
  7099. except TypeError:
  7100. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  7101. filename = str(filename)
  7102. if filename == "":
  7103. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7104. return
  7105. else:
  7106. self.export_dxf(name, filename)
  7107. if self.defaults["global_open_style"] is False:
  7108. self.app.file_opened.emit("DXF", filename)
  7109. self.app.file_saved.emit("DXF", filename)
  7110. def on_file_importsvg(self, type_of_obj):
  7111. """
  7112. Callback for menu item File->Import SVG.
  7113. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7114. :type type_of_obj: str
  7115. :return: None
  7116. """
  7117. self.app.log.debug("on_file_importsvg()")
  7118. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7119. try:
  7120. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7121. directory=self.app.get_last_folder(),
  7122. filter=_filter_)
  7123. except TypeError:
  7124. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7125. filter=_filter_)
  7126. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7127. type_of_obj = "geometry"
  7128. filenames = [str(filename) for filename in filenames]
  7129. if len(filenames) == 0:
  7130. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7131. else:
  7132. for filename in filenames:
  7133. if filename != '':
  7134. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7135. def on_file_importdxf(self, type_of_obj):
  7136. """
  7137. Callback for menu item File->Import DXF.
  7138. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7139. :type type_of_obj: str
  7140. :return: None
  7141. """
  7142. self.app.log.debug("on_file_importdxf()")
  7143. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7144. try:
  7145. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7146. directory=self.app.get_last_folder(),
  7147. filter=_filter_)
  7148. except TypeError:
  7149. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7150. filter=_filter_)
  7151. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7152. type_of_obj = "geometry"
  7153. filenames = [str(filename) for filename in filenames]
  7154. if len(filenames) == 0:
  7155. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7156. else:
  7157. for filename in filenames:
  7158. if filename != '':
  7159. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7160. def on_file_new_click(self):
  7161. """
  7162. Callback for menu item File -> New.
  7163. Executed on clicking the Menu -> File -> New Project
  7164. :return:
  7165. """
  7166. if self.app.collection.get_list() and self.app.should_we_save:
  7167. msgbox = QtWidgets.QMessageBox()
  7168. # msgbox.setText("<B>Save changes ...</B>")
  7169. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7170. "Creating a New project will delete them.\n"
  7171. "Do you want to Save the project?"))
  7172. msgbox.setWindowTitle(_("Save changes"))
  7173. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7174. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7175. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7176. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7177. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7178. msgbox.setDefaultButton(bt_yes)
  7179. msgbox.exec_()
  7180. response = msgbox.clickedButton()
  7181. if response == bt_yes:
  7182. self.on_file_saveprojectas()
  7183. elif response == bt_cancel:
  7184. return
  7185. elif response == bt_no:
  7186. self.on_file_new()
  7187. else:
  7188. self.on_file_new()
  7189. self.inform.emit('[success] %s...' % _("New Project created"))
  7190. def on_file_new(self, cli=None):
  7191. """
  7192. Returns the application to its startup state. This method is thread-safe.
  7193. :param cli: Boolean. If True this method was run from command line
  7194. :return: None
  7195. """
  7196. self.defaults.report_usage("on_file_new")
  7197. # Remove everything from memory
  7198. self.app.log.debug("on_file_new()")
  7199. # close any editor that might be open
  7200. if self.app.call_source != 'app':
  7201. self.app.editor2object(cleanup=True)
  7202. # ## EDITOR section
  7203. self.app.geo_editor = AppGeoEditor(self.app)
  7204. self.app.exc_editor = AppExcEditor(self.app)
  7205. self.app.grb_editor = AppGerberEditor(self.app)
  7206. # Clear pool
  7207. self.app.clear_pool()
  7208. for obj in self.app.collection.get_list():
  7209. # delete shapes left drawn from mark shape_collections, if any
  7210. if isinstance(obj, GerberObject):
  7211. try:
  7212. obj.mark_shapes_storage.clear()
  7213. obj.mark_shapes.clear(update=True)
  7214. obj.mark_shapes.enabled = False
  7215. except AttributeError:
  7216. pass
  7217. # also delete annotation shapes, if any
  7218. elif isinstance(obj, CNCJobObject):
  7219. try:
  7220. obj.text_col.enabled = False
  7221. del obj.text_col
  7222. obj.annotation.clear(update=True)
  7223. del obj.annotation
  7224. except AttributeError:
  7225. pass
  7226. # delete the exclusion areas
  7227. self.app.exc_areas.clear_shapes()
  7228. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7229. self.app.shell.init_tcl()
  7230. # delete any selection shape on canvas
  7231. self.app.delete_selection_shape()
  7232. # delete all FlatCAM objects
  7233. self.app.collection.delete_all()
  7234. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7235. self.app.setup_default_properties_tab()
  7236. # Clear project filename
  7237. self.app.project_filename = None
  7238. # Load the application defaults
  7239. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7240. # Re-fresh project options
  7241. self.app.on_options_app2project()
  7242. # Init FlatCAMTools
  7243. self.app.init_tools()
  7244. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7245. if cli is None:
  7246. # we need to go in reverse because once we remove a tab then the index changes
  7247. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7248. # and so on. Therefore the deletion should be done in reverse
  7249. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7250. for index in range(wdg_count, -1, -1):
  7251. try:
  7252. self.app.ui.plot_tab_area.closeTab(index)
  7253. except Exception as e:
  7254. log.debug("App.on_file_new() --> %s" % str(e))
  7255. # # And then add again the Plot Area
  7256. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7257. self.app.ui.plot_tab_area.protectTab(0)
  7258. # take the focus of the Notebook on Project Tab.
  7259. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7260. self.app.set_ui_title(name=_("New Project - Not saved"))
  7261. def on_filenewscript(self, silent=False):
  7262. """
  7263. Will create a new script file and open it in the Code Editor
  7264. :param silent: if True will not display status messages
  7265. :return: None
  7266. """
  7267. if silent is False:
  7268. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7269. # hide coordinates toolbars in the infobar while in DB
  7270. self.app.ui.coords_toolbar.hide()
  7271. self.app.ui.delta_coords_toolbar.hide()
  7272. self.app.app_obj.new_script_object()
  7273. def on_fileopenscript(self, name=None, silent=False):
  7274. """
  7275. Will open a Tcl script file into the Code Editor
  7276. :param silent: if True will not display status messages
  7277. :param name: name of a Tcl script file to open
  7278. :return: None
  7279. """
  7280. self.app.log.debug("on_fileopenscript()")
  7281. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7282. "All Files (*.*)"
  7283. if name:
  7284. filenames = [name]
  7285. else:
  7286. try:
  7287. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7288. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7289. except TypeError:
  7290. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7291. if len(filenames) == 0:
  7292. if silent is False:
  7293. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7294. else:
  7295. for filename in filenames:
  7296. if filename != '':
  7297. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7298. def on_fileopenscript_example(self, name=None, silent=False):
  7299. """
  7300. Will open a Tcl script file into the Code Editor
  7301. :param silent: if True will not display status messages
  7302. :param name: name of a Tcl script file to open
  7303. :return:
  7304. """
  7305. self.app.log.debug("on_fileopenscript_example()")
  7306. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7307. "All Files (*.*)"
  7308. # test if the app was frozen and choose the path for the configuration file
  7309. if getattr(sys, "frozen", False) is True:
  7310. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7311. else:
  7312. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7313. if name:
  7314. filenames = [name]
  7315. else:
  7316. try:
  7317. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7318. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7319. except TypeError:
  7320. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7321. if len(filenames) == 0:
  7322. if silent is False:
  7323. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7324. else:
  7325. for filename in filenames:
  7326. if filename != '':
  7327. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7328. def on_filerunscript(self, name=None, silent=False):
  7329. """
  7330. File menu callback for loading and running a TCL script.
  7331. :param silent: if True will not display status messages
  7332. :param name: name of a Tcl script file to be run by FlatCAM
  7333. :return: None
  7334. """
  7335. self.app.log.debug("on_file_runscript()")
  7336. if name:
  7337. filename = name
  7338. if self.app.cmd_line_headless != 1:
  7339. self.splash.showMessage('%s: %ssec\n%s' %
  7340. (_("Canvas initialization started.\n"
  7341. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7342. _("Executing ScriptObject file.")
  7343. ),
  7344. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7345. color=QtGui.QColor("gray"))
  7346. else:
  7347. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7348. "All Files (*.*)"
  7349. try:
  7350. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7351. directory=self.app.get_last_folder(),
  7352. filter=_filter_)
  7353. except TypeError:
  7354. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7355. # The Qt methods above will return a QString which can cause problems later.
  7356. # So far json.dump() will fail to serialize it.
  7357. filename = str(filename)
  7358. if filename == "":
  7359. if silent is False:
  7360. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7361. else:
  7362. if self.app.cmd_line_headless != 1:
  7363. if self.app.ui.shell_dock.isHidden():
  7364. self.app.ui.shell_dock.show()
  7365. try:
  7366. with open(filename, "r") as tcl_script:
  7367. cmd_line_shellfile_content = tcl_script.read()
  7368. if self.app.cmd_line_headless != 1:
  7369. self.app.shell.exec_command(cmd_line_shellfile_content)
  7370. else:
  7371. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7372. if silent is False:
  7373. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7374. except Exception as e:
  7375. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7376. sys.exit(2)
  7377. def on_file_saveproject(self, silent=False):
  7378. """
  7379. Callback for menu item File->Save Project. Saves the project to
  7380. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7381. if set to None. The project is saved by calling ``self.save_project()``.
  7382. :param silent: if True will not display status messages
  7383. :return: None
  7384. """
  7385. if self.app.project_filename is None:
  7386. self.on_file_saveprojectas()
  7387. else:
  7388. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7389. if self.defaults["global_open_style"] is False:
  7390. self.app.file_opened.emit("project", self.project_filename)
  7391. self.app.file_saved.emit("project", self.project_filename)
  7392. self.app.set_ui_title(name=self.app.project_filename)
  7393. self.app.should_we_save = False
  7394. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7395. """
  7396. Callback for menu item File->Save Project As... Opens a file
  7397. chooser and saves the project to the given file via
  7398. ``self.save_project()``.
  7399. :param make_copy if to be create a copy of the project; boolean
  7400. :param use_thread: if to be run in a separate thread; boolean
  7401. :param quit_action: if to be followed by quiting the application; boolean
  7402. :return: None
  7403. """
  7404. date = str(datetime.today()).rpartition('.')[0]
  7405. date = ''.join(c for c in date if c not in ':-')
  7406. date = date.replace(' ', '_')
  7407. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7408. try:
  7409. filename, _f = FCFileSaveDialog.get_saved_filename(
  7410. caption=_("Save Project As ..."),
  7411. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7412. proj=_("Project")),
  7413. ext_filter=filter_
  7414. )
  7415. except TypeError:
  7416. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  7417. filename = str(filename)
  7418. if filename == '':
  7419. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7420. return
  7421. if use_thread is True:
  7422. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7423. else:
  7424. self.save_project(filename, quit_action)
  7425. # self.save_project(filename)
  7426. if self.defaults["global_open_style"] is False:
  7427. self.app.file_opened.emit("project", filename)
  7428. self.app.file_saved.emit("project", filename)
  7429. if not make_copy:
  7430. self.app.project_filename = filename
  7431. self.app.set_ui_title(name=self.app.project_filename)
  7432. self.app.should_we_save = False
  7433. def on_file_save_objects_pdf(self, use_thread=True):
  7434. date = str(datetime.today()).rpartition('.')[0]
  7435. date = ''.join(c for c in date if c not in ':-')
  7436. date = date.replace(' ', '_')
  7437. try:
  7438. obj_selection = self.app.collection.get_selected()
  7439. if len(obj_selection) == 1:
  7440. obj_name = str(obj_selection[0].options['name'])
  7441. else:
  7442. obj_name = _("FlatCAM objects print")
  7443. except AttributeError as err:
  7444. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7445. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7446. return
  7447. if not obj_selection:
  7448. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7449. return
  7450. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7451. try:
  7452. filename, _f = FCFileSaveDialog.get_saved_filename(
  7453. caption=_("Save Object as PDF ..."),
  7454. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7455. obj_name=obj_name,
  7456. date=date),
  7457. ext_filter=filter_
  7458. )
  7459. except TypeError:
  7460. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  7461. filename = str(filename)
  7462. if filename == '':
  7463. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7464. return
  7465. if use_thread is True:
  7466. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7467. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7468. else:
  7469. self.save_pdf(filename, obj_selection)
  7470. # self.save_project(filename)
  7471. if self.defaults["global_open_style"] is False:
  7472. self.app.file_opened.emit("pdf", filename)
  7473. self.app.file_saved.emit("pdf", filename)
  7474. def save_pdf(self, file_name, obj_selection):
  7475. p_size = self.defaults['global_workspaceT']
  7476. orientation = self.defaults['global_workspace_orientation']
  7477. color = 'black'
  7478. transparency_level = 1.0
  7479. self.pagesize.update(
  7480. {
  7481. 'Bounds': None,
  7482. 'A0': (841 * mm, 1189 * mm),
  7483. 'A1': (594 * mm, 841 * mm),
  7484. 'A2': (420 * mm, 594 * mm),
  7485. 'A3': (297 * mm, 420 * mm),
  7486. 'A4': (210 * mm, 297 * mm),
  7487. 'A5': (148 * mm, 210 * mm),
  7488. 'A6': (105 * mm, 148 * mm),
  7489. 'A7': (74 * mm, 105 * mm),
  7490. 'A8': (52 * mm, 74 * mm),
  7491. 'A9': (37 * mm, 52 * mm),
  7492. 'A10': (26 * mm, 37 * mm),
  7493. 'B0': (1000 * mm, 1414 * mm),
  7494. 'B1': (707 * mm, 1000 * mm),
  7495. 'B2': (500 * mm, 707 * mm),
  7496. 'B3': (353 * mm, 500 * mm),
  7497. 'B4': (250 * mm, 353 * mm),
  7498. 'B5': (176 * mm, 250 * mm),
  7499. 'B6': (125 * mm, 176 * mm),
  7500. 'B7': (88 * mm, 125 * mm),
  7501. 'B8': (62 * mm, 88 * mm),
  7502. 'B9': (44 * mm, 62 * mm),
  7503. 'B10': (31 * mm, 44 * mm),
  7504. 'C0': (917 * mm, 1297 * mm),
  7505. 'C1': (648 * mm, 917 * mm),
  7506. 'C2': (458 * mm, 648 * mm),
  7507. 'C3': (324 * mm, 458 * mm),
  7508. 'C4': (229 * mm, 324 * mm),
  7509. 'C5': (162 * mm, 229 * mm),
  7510. 'C6': (114 * mm, 162 * mm),
  7511. 'C7': (81 * mm, 114 * mm),
  7512. 'C8': (57 * mm, 81 * mm),
  7513. 'C9': (40 * mm, 57 * mm),
  7514. 'C10': (28 * mm, 40 * mm),
  7515. # American paper sizes
  7516. 'LETTER': (8.5 * inch, 11 * inch),
  7517. 'LEGAL': (8.5 * inch, 14 * inch),
  7518. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7519. # From https://en.wikipedia.org/wiki/Paper_size
  7520. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7521. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7522. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7523. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7524. 'LEDGER': (17 * inch, 11 * inch),
  7525. }
  7526. )
  7527. exported_svg = []
  7528. for obj in obj_selection:
  7529. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7530. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7531. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7532. color = obj.fill_color[:-2]
  7533. transparency_level = obj.fill_color[-2:]
  7534. elif obj.kind.lower() == 'geometry':
  7535. color = self.defaults["global_draw_color"]
  7536. # Change the attributes of the exported SVG
  7537. # We don't need stroke-width
  7538. # We set opacity to maximum
  7539. # We set the colour to WHITE
  7540. root = ET.fromstring(svg_obj)
  7541. for child in root:
  7542. child.set('fill', str(color))
  7543. child.set('opacity', str(transparency_level))
  7544. child.set('stroke', str(color))
  7545. exported_svg.append(ET.tostring(root))
  7546. xmin = Inf
  7547. ymin = Inf
  7548. xmax = -Inf
  7549. ymax = -Inf
  7550. for obj in obj_selection:
  7551. try:
  7552. gxmin, gymin, gxmax, gymax = obj.bounds()
  7553. xmin = min([xmin, gxmin])
  7554. ymin = min([ymin, gymin])
  7555. xmax = max([xmax, gxmax])
  7556. ymax = max([ymax, gymax])
  7557. except Exception as e:
  7558. self.app.log.warning(
  7559. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7560. # Determine bounding area for svg export
  7561. bounds = [xmin, ymin, xmax, ymax]
  7562. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7563. # This contain the measure units
  7564. uom = obj_selection[0].units.lower()
  7565. # Define a boundary around SVG of about 1.0mm (~39mils)
  7566. if uom in "mm":
  7567. boundary = 1.0
  7568. else:
  7569. boundary = 0.0393701
  7570. # Convert everything to strings for use in the xml doc
  7571. svgwidth = str(size[0] + (2 * boundary))
  7572. svgheight = str(size[1] + (2 * boundary))
  7573. minx = str(bounds[0] - boundary)
  7574. miny = str(bounds[1] + boundary + size[1])
  7575. # Add a SVG Header and footer to the svg output from shapely
  7576. # The transform flips the Y Axis so that everything renders
  7577. # properly within svg apps such as inkscape
  7578. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7579. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7580. svg_header += 'width="' + svgwidth + uom + '" '
  7581. svg_header += 'height="' + svgheight + uom + '" '
  7582. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7583. svg_header += '>'
  7584. svg_header += '<g transform="scale(1,-1)">'
  7585. svg_footer = '</g> </svg>'
  7586. svg_elem = str(svg_header)
  7587. for svg_item in exported_svg:
  7588. svg_elem += str(svg_item)
  7589. svg_elem += str(svg_footer)
  7590. # Parse the xml through a xml parser just to add line feeds
  7591. # and to make it look more pretty for the output
  7592. doc = parse_xml_string(svg_elem)
  7593. doc_final = doc.toprettyxml()
  7594. try:
  7595. if self.defaults['units'].upper() == 'IN':
  7596. unit = inch
  7597. else:
  7598. unit = mm
  7599. doc_final = StringIO(doc_final)
  7600. drawing = svg2rlg(doc_final)
  7601. if p_size == 'Bounds':
  7602. renderPDF.drawToFile(drawing, file_name)
  7603. else:
  7604. if orientation == 'p':
  7605. page_size = portrait(self.pagesize[p_size])
  7606. else:
  7607. page_size = landscape(self.pagesize[p_size])
  7608. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7609. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7610. renderPDF.draw(drawing, my_canvas, 0, 0)
  7611. my_canvas.save()
  7612. except Exception as e:
  7613. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7614. return 'fail'
  7615. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7616. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7617. """
  7618. Exports a Geometry Object to an SVG file.
  7619. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7620. :param filename: Path to the SVG file to save to.
  7621. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7622. :return:
  7623. """
  7624. if filename is None:
  7625. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7626. is not None else self.defaults["global_last_folder"]
  7627. self.app.log.debug("export_svg()")
  7628. try:
  7629. obj = self.app.collection.get_by_name(str(obj_name))
  7630. except Exception:
  7631. return 'fail'
  7632. with self.app.proc_container.new(_("Exporting SVG")):
  7633. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7634. # Determine bounding area for svg export
  7635. bounds = obj.bounds()
  7636. size = obj.size()
  7637. # Convert everything to strings for use in the xml doc
  7638. svgwidth = str(size[0])
  7639. svgheight = str(size[1])
  7640. minx = str(bounds[0])
  7641. miny = str(bounds[1] - size[1])
  7642. uom = obj.units.lower()
  7643. # Add a SVG Header and footer to the svg output from shapely
  7644. # The transform flips the Y Axis so that everything renders
  7645. # properly within svg apps such as inkscape
  7646. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7647. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7648. svg_header += 'width="' + svgwidth + uom + '" '
  7649. svg_header += 'height="' + svgheight + uom + '" '
  7650. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7651. svg_header += '<g transform="scale(1,-1)">'
  7652. svg_footer = '</g> </svg>'
  7653. svg_elem = svg_header + exported_svg + svg_footer
  7654. # Parse the xml through a xml parser just to add line feeds
  7655. # and to make it look more pretty for the output
  7656. svgcode = parse_xml_string(svg_elem)
  7657. svgcode = svgcode.toprettyxml()
  7658. try:
  7659. with open(filename, 'w') as fp:
  7660. fp.write(svgcode)
  7661. except PermissionError:
  7662. self.inform.emit('[WARNING] %s' %
  7663. _("Permission denied, saving not possible.\n"
  7664. "Most likely another app is holding the file open and not accessible."))
  7665. return 'fail'
  7666. if self.defaults["global_open_style"] is False:
  7667. self.app.file_opened.emit("SVG", filename)
  7668. self.app.file_saved.emit("SVG", filename)
  7669. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7670. def on_import_preferences(self):
  7671. """
  7672. Loads the application default settings from a saved file into
  7673. ``self.defaults`` dictionary.
  7674. :return: None
  7675. """
  7676. self.app.log.debug("App.on_import_preferences()")
  7677. # Show file chooser
  7678. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7679. try:
  7680. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7681. directory=self.app.data_path,
  7682. filter=filter_)
  7683. except TypeError:
  7684. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7685. filter=filter_)
  7686. filename = str(filename)
  7687. if filename == "":
  7688. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7689. return
  7690. # Load in the defaults from the chosen file
  7691. self.defaults.load(filename=filename, inform=self.inform)
  7692. self.app.preferencesUiManager.on_preferences_edited()
  7693. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7694. def on_export_preferences(self):
  7695. """
  7696. Save the defaults dictionary to a file.
  7697. :return: None
  7698. """
  7699. self.app.log.debug("on_export_preferences()")
  7700. # defaults_file_content = None
  7701. # Show file chooser
  7702. date = str(datetime.today()).rpartition('.')[0]
  7703. date = ''.join(c for c in date if c not in ':-')
  7704. date = date.replace(' ', '_')
  7705. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7706. try:
  7707. filename, _f = FCFileSaveDialog.get_saved_filename(
  7708. caption=_("Export FlatCAM Preferences"),
  7709. directory=self.app.data_path + '/preferences_' + date,
  7710. ext_filter=filter__
  7711. )
  7712. except TypeError:
  7713. filename, _f = FCFileSaveDialog.get_saved_filename(
  7714. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7715. filename = str(filename)
  7716. if filename == "":
  7717. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7718. return 'fail'
  7719. # Update options
  7720. self.app.preferencesUiManager.defaults_read_form()
  7721. self.defaults.propagate_defaults()
  7722. # Save update options
  7723. try:
  7724. self.defaults.write(filename=filename)
  7725. except Exception:
  7726. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7727. return
  7728. if self.defaults["global_open_style"] is False:
  7729. self.app.file_opened.emit("preferences", filename)
  7730. self.app.file_saved.emit("preferences", filename)
  7731. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7732. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7733. """
  7734. Exports a Excellon Object to an Excellon file.
  7735. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7736. :param filename: Path to the Excellon file to save to.
  7737. :param local_use:
  7738. :param use_thread: if to be run in a separate thread
  7739. :return:
  7740. """
  7741. if filename is None:
  7742. if self.defaults["global_last_save_folder"]:
  7743. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7744. else:
  7745. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7746. self.app.log.debug("export_excellon()")
  7747. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7748. self.defaults["excellon_exp_decimals"]
  7749. )
  7750. if local_use is None:
  7751. try:
  7752. obj = self.app.collection.get_by_name(str(obj_name))
  7753. except Exception:
  7754. return "Could not retrieve object: %s" % obj_name
  7755. else:
  7756. obj = local_use
  7757. if not isinstance(obj, ExcellonObject):
  7758. self.inform.emit('[ERROR_NOTCL] %s' %
  7759. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7760. return
  7761. # updated units
  7762. eunits = self.defaults["excellon_exp_units"]
  7763. ewhole = self.defaults["excellon_exp_integer"]
  7764. efract = self.defaults["excellon_exp_decimals"]
  7765. ezeros = self.defaults["excellon_exp_zeros"]
  7766. eformat = self.defaults["excellon_exp_format"]
  7767. slot_type = self.defaults["excellon_exp_slot_type"]
  7768. fc_units = self.defaults['units'].upper()
  7769. if fc_units == 'MM':
  7770. factor = 1 if eunits == 'METRIC' else 0.03937
  7771. else:
  7772. factor = 25.4 if eunits == 'METRIC' else 1
  7773. def make_excellon():
  7774. try:
  7775. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7776. header = 'M48\n'
  7777. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7778. (str(self.app.version), str(self.app.version_date))
  7779. header += ';Filename: %s' % str(obj_name) + '\n'
  7780. header += ';Created on : %s' % time_str + '\n'
  7781. if eformat == 'dec':
  7782. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7783. header += eunits + '\n'
  7784. for tool in obj.tools:
  7785. if eunits == 'METRIC':
  7786. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7787. tool=str(tool),
  7788. dec=2)
  7789. else:
  7790. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7791. tool=str(tool),
  7792. dec=4)
  7793. else:
  7794. if ezeros == 'LZ':
  7795. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7796. form='ndec', e_zeros='LZ', factor=factor,
  7797. slot_type=slot_type)
  7798. header += '%s,%s\n' % (eunits, 'LZ')
  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. else:
  7812. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7813. form='ndec', e_zeros='TZ', factor=factor,
  7814. slot_type=slot_type)
  7815. header += '%s,%s\n' % (eunits, 'TZ')
  7816. header += format_exc
  7817. for tool in obj.tools:
  7818. if eunits == 'METRIC':
  7819. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7820. float(obj.tools[tool]['tooldia']) * factor,
  7821. tool=str(tool),
  7822. dec=2)
  7823. else:
  7824. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7825. float(obj.tools[tool]['tooldia']) * factor,
  7826. tool=str(tool),
  7827. dec=4)
  7828. header += '%\n'
  7829. footer = 'M30\n'
  7830. exported_excellon = header
  7831. exported_excellon += excellon_code
  7832. exported_excellon += footer
  7833. if local_use is None:
  7834. try:
  7835. with open(filename, 'w') as fp:
  7836. fp.write(exported_excellon)
  7837. except PermissionError:
  7838. self.inform.emit('[WARNING] %s' %
  7839. _("Permission denied, saving not possible.\n"
  7840. "Most likely another app is holding the file open and not accessible."))
  7841. return 'fail'
  7842. if self.defaults["global_open_style"] is False:
  7843. self.app.file_opened.emit("Excellon", filename)
  7844. self.app.file_saved.emit("Excellon", filename)
  7845. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7846. else:
  7847. return exported_excellon
  7848. except Exception as e:
  7849. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7850. return 'fail'
  7851. if use_thread is True:
  7852. with self.app.proc_container.new(_("Exporting Excellon")):
  7853. def job_thread_exc(app_obj):
  7854. ret = make_excellon()
  7855. if ret == 'fail':
  7856. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7857. return
  7858. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7859. else:
  7860. eret = make_excellon()
  7861. if eret == 'fail':
  7862. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7863. return 'fail'
  7864. if local_use is not None:
  7865. return eret
  7866. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7867. """
  7868. Exports a Gerber Object to an Gerber file.
  7869. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7870. :param filename: Path to the Gerber file to save to.
  7871. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7872. When not None, the value will be the actual Gerber object for which to create
  7873. the Gerber code
  7874. :param use_thread: if to be run in a separate thread
  7875. :return:
  7876. """
  7877. if filename is None:
  7878. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7879. is not None else self.defaults["global_last_folder"]
  7880. self.app.log.debug("export_gerber()")
  7881. if local_use is None:
  7882. try:
  7883. obj = self.app.collection.get_by_name(str(obj_name))
  7884. except Exception:
  7885. return 'fail'
  7886. else:
  7887. obj = local_use
  7888. # updated units
  7889. gunits = self.defaults["gerber_exp_units"]
  7890. gwhole = self.defaults["gerber_exp_integer"]
  7891. gfract = self.defaults["gerber_exp_decimals"]
  7892. gzeros = self.defaults["gerber_exp_zeros"]
  7893. fc_units = self.defaults['units'].upper()
  7894. if fc_units == 'MM':
  7895. factor = 1 if gunits == 'MM' else 0.03937
  7896. else:
  7897. factor = 25.4 if gunits == 'MM' else 1
  7898. def make_gerber():
  7899. try:
  7900. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7901. header = 'G04*\n'
  7902. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7903. (str(self.app.version), str(self.app.version_date))
  7904. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7905. header += 'G04 Created on : %s*' % time_str + '\n'
  7906. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7907. header += "%MO{units}*%\n".format(units=gunits)
  7908. for apid in obj.apertures:
  7909. if obj.apertures[apid]['type'] == 'C':
  7910. header += "%ADD{apid}{type},{size}*%\n".format(
  7911. apid=str(apid),
  7912. type='C',
  7913. size=(factor * obj.apertures[apid]['size'])
  7914. )
  7915. elif obj.apertures[apid]['type'] == 'R':
  7916. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7917. apid=str(apid),
  7918. type='R',
  7919. width=(factor * obj.apertures[apid]['width']),
  7920. height=(factor * obj.apertures[apid]['height'])
  7921. )
  7922. elif obj.apertures[apid]['type'] == 'O':
  7923. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7924. apid=str(apid),
  7925. type='O',
  7926. width=(factor * obj.apertures[apid]['width']),
  7927. height=(factor * obj.apertures[apid]['height'])
  7928. )
  7929. header += '\n'
  7930. # obsolete units but some software may need it
  7931. if gunits == 'IN':
  7932. header += 'G70*\n'
  7933. else:
  7934. header += 'G71*\n'
  7935. # Absolute Mode
  7936. header += 'G90*\n'
  7937. header += 'G01*\n'
  7938. # positive polarity
  7939. header += '%LPD*%\n'
  7940. footer = 'M02*\n'
  7941. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7942. exported_gerber = header
  7943. exported_gerber += gerber_code
  7944. exported_gerber += footer
  7945. if local_use is None:
  7946. try:
  7947. with open(filename, 'w') as fp:
  7948. fp.write(exported_gerber)
  7949. except PermissionError:
  7950. self.inform.emit('[WARNING] %s' %
  7951. _("Permission denied, saving not possible.\n"
  7952. "Most likely another app is holding the file open and not accessible."))
  7953. return 'fail'
  7954. if self.defaults["global_open_style"] is False:
  7955. self.app.file_opened.emit("Gerber", filename)
  7956. self.app.file_saved.emit("Gerber", filename)
  7957. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7958. else:
  7959. return exported_gerber
  7960. except Exception as e:
  7961. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7962. return 'fail'
  7963. if use_thread is True:
  7964. with self.app.proc_container.new(_("Exporting Gerber")):
  7965. def job_thread_grb(app_obj):
  7966. ret = make_gerber()
  7967. if ret == 'fail':
  7968. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7969. return
  7970. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7971. else:
  7972. gret = make_gerber()
  7973. if gret == 'fail':
  7974. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  7975. return 'fail'
  7976. if local_use is not None:
  7977. return gret
  7978. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7979. """
  7980. Exports a Geometry Object to an DXF file.
  7981. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7982. :param filename: Path to the DXF file to save to.
  7983. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7984. When not None, the value will be the actual Geometry object for which to create
  7985. the Geometry/DXF code
  7986. :param use_thread: if to be run in a separate thread
  7987. :return:
  7988. """
  7989. if filename is None:
  7990. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7991. is not None else self.defaults["global_last_folder"]
  7992. self.app.log.debug("export_dxf()")
  7993. if local_use is None:
  7994. try:
  7995. obj = self.app.collection.get_by_name(str(obj_name))
  7996. except Exception:
  7997. return 'fail'
  7998. else:
  7999. obj = local_use
  8000. def make_dxf():
  8001. try:
  8002. dxf_code = obj.export_dxf()
  8003. if local_use is None:
  8004. try:
  8005. dxf_code.saveas(filename)
  8006. except PermissionError:
  8007. self.inform.emit('[WARNING] %s' %
  8008. _("Permission denied, saving not possible.\n"
  8009. "Most likely another app is holding the file open and not accessible."))
  8010. return 'fail'
  8011. if self.defaults["global_open_style"] is False:
  8012. self.app.file_opened.emit("DXF", filename)
  8013. self.app.file_saved.emit("DXF", filename)
  8014. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8015. else:
  8016. return dxf_code
  8017. except Exception as e:
  8018. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8019. return 'fail'
  8020. if use_thread is True:
  8021. with self.app.proc_container.new(_("Exporting DXF")):
  8022. def job_thread_exc(app_obj):
  8023. ret_dxf_val = make_dxf()
  8024. if ret_dxf_val == 'fail':
  8025. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8026. return
  8027. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8028. else:
  8029. ret = make_dxf()
  8030. if ret == 'fail':
  8031. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8032. return
  8033. if local_use is not None:
  8034. return ret
  8035. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8036. """
  8037. Adds a new Geometry Object to the projects and populates
  8038. it with shapes extracted from the SVG file.
  8039. :param plot: If True then the resulting object will be plotted on canvas
  8040. :param filename: Path to the SVG file.
  8041. :param geo_type: Type of FlatCAM object that will be created from SVG
  8042. :param outname: The name given to the resulting FlatCAM object
  8043. :return:
  8044. """
  8045. self.app.log.debug("App.import_svg()")
  8046. obj_type = ""
  8047. if geo_type is None or geo_type == "geometry":
  8048. obj_type = "geometry"
  8049. elif geo_type == "gerber":
  8050. obj_type = "gerber"
  8051. else:
  8052. self.inform.emit('[ERROR_NOTCL] %s' %
  8053. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8054. return
  8055. units = self.defaults['units'].upper()
  8056. def obj_init(geo_obj, app_obj):
  8057. geo_obj.import_svg(filename, obj_type, units=units)
  8058. geo_obj.multigeo = True
  8059. with open(filename) as f:
  8060. file_content = f.read()
  8061. geo_obj.source_file = file_content
  8062. # appGUI feedback
  8063. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8064. with self.app.proc_container.new(_("Importing SVG")):
  8065. # Object name
  8066. name = outname or filename.split('/')[-1].split('\\')[-1]
  8067. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8068. if ret == 'fail':
  8069. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8070. return 'fail'
  8071. # Register recent file
  8072. self.app.file_opened.emit("svg", filename)
  8073. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8074. """
  8075. Adds a new Geometry Object to the projects and populates
  8076. it with shapes extracted from the DXF file.
  8077. :param filename: Path to the DXF file.
  8078. :param geo_type: Type of FlatCAM object that will be created from DXF
  8079. :param outname: Name for the imported Geometry
  8080. :param plot: If True then the resulting object will be plotted on canvas
  8081. :return:
  8082. """
  8083. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8084. obj_type = ""
  8085. if geo_type is None or geo_type == "geometry":
  8086. obj_type = "geometry"
  8087. elif geo_type == "gerber":
  8088. obj_type = geo_type
  8089. else:
  8090. self.inform.emit('[ERROR_NOTCL] %s' %
  8091. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8092. return
  8093. units = self.defaults['units'].upper()
  8094. def obj_init(geo_obj, app_obj):
  8095. if obj_type == "geometry":
  8096. geo_obj.import_dxf_as_geo(filename, units=units)
  8097. elif obj_type == "gerber":
  8098. geo_obj.import_dxf_as_gerber(filename, units=units)
  8099. else:
  8100. return "fail"
  8101. geo_obj.multigeo = True
  8102. with open(filename) as f:
  8103. file_content = f.read()
  8104. geo_obj.source_file = file_content
  8105. # appGUI feedback
  8106. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8107. with self.app.proc_container.new(_("Importing DXF")):
  8108. # Object name
  8109. name = outname or filename.split('/')[-1].split('\\')[-1]
  8110. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8111. if ret == 'fail':
  8112. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8113. return 'fail'
  8114. # Register recent file
  8115. self.app.file_opened.emit("dxf", filename)
  8116. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8117. """
  8118. Opens a Gerber file, parses it and creates a new object for
  8119. it in the program. Thread-safe.
  8120. :param outname: Name of the resulting object. None causes the
  8121. name to be that of the file. Str.
  8122. :param filename: Gerber file filename
  8123. :type filename: str
  8124. :param plot: boolean, to plot or not the resulting object
  8125. :param from_tcl: True if run from Tcl Shell
  8126. :return: None
  8127. """
  8128. # How the object should be initialized
  8129. def obj_init(gerber_obj, app_obj):
  8130. assert isinstance(gerber_obj, GerberObject), \
  8131. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8132. # Opening the file happens here
  8133. try:
  8134. gerber_obj.parse_file(filename)
  8135. except IOError:
  8136. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8137. return "fail"
  8138. except ParseError as err:
  8139. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8140. app_obj.log.error(str(err))
  8141. return "fail"
  8142. except Exception as e:
  8143. log.debug("App.open_gerber() --> %s" % str(e))
  8144. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8145. msg += traceback.format_exc()
  8146. app_obj.inform.emit(msg)
  8147. return "fail"
  8148. if gerber_obj.is_empty():
  8149. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8150. _("Object is not Gerber file or empty. Aborting object creation."))
  8151. return "fail"
  8152. self.app.log.debug("open_gerber()")
  8153. with self.app.proc_container.new(_("Opening Gerber")):
  8154. # Object name
  8155. name = outname or filename.split('/')[-1].split('\\')[-1]
  8156. # # ## Object creation # ##
  8157. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8158. if ret_val == 'fail':
  8159. if from_tcl:
  8160. filename = self.defaults['global_tcl_path'] + '/' + name
  8161. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8162. if ret_val == 'fail':
  8163. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8164. return 'fail'
  8165. # Register recent file
  8166. self.app.file_opened.emit("gerber", filename)
  8167. # appGUI feedback
  8168. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8169. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8170. """
  8171. Opens an Excellon file, parses it and creates a new object for
  8172. it in the program. Thread-safe.
  8173. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8174. :param filename: Excellon file filename
  8175. :type filename: str
  8176. :param plot: boolean, to plot or not the resulting object
  8177. :param from_tcl: True if run from Tcl Shell
  8178. :return: None
  8179. """
  8180. self.app.log.debug("open_excellon()")
  8181. # How the object should be initialized
  8182. def obj_init(excellon_obj, app_obj):
  8183. try:
  8184. ret = excellon_obj.parse_file(filename=filename)
  8185. if ret == "fail":
  8186. app_obj.log.debug("Excellon parsing failed.")
  8187. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8188. return "fail"
  8189. except IOError:
  8190. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8191. app_obj.log.debug("Could not open Excellon object.")
  8192. return "fail"
  8193. except Exception:
  8194. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8195. msg += traceback.format_exc()
  8196. app_obj.inform.emit(msg)
  8197. return "fail"
  8198. ret = excellon_obj.create_geometry()
  8199. if ret == 'fail':
  8200. app_obj.log.debug("Could not create geometry for Excellon object.")
  8201. return "fail"
  8202. for tool in excellon_obj.tools:
  8203. if excellon_obj.tools[tool]['solid_geometry']:
  8204. return
  8205. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8206. return "fail"
  8207. with self.app.proc_container.new(_("Opening Excellon.")):
  8208. # Object name
  8209. name = outname or filename.split('/')[-1].split('\\')[-1]
  8210. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8211. if ret_val == 'fail':
  8212. if from_tcl:
  8213. filename = self.defaults['global_tcl_path'] + '/' + name
  8214. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8215. if ret_val == 'fail':
  8216. self.inform.emit('[ERROR_NOTCL] %s' %
  8217. _('Open Excellon file failed. Probable not an Excellon file.'))
  8218. return
  8219. # Register recent file
  8220. self.app.file_opened.emit("excellon", filename)
  8221. # appGUI feedback
  8222. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8223. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8224. """
  8225. Opens a G-gcode file, parses it and creates a new object for
  8226. it in the program. Thread-safe.
  8227. :param filename: G-code file filename
  8228. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8229. :param force_parsing:
  8230. :param plot: If True plot the object on canvas
  8231. :param from_tcl: True if run from Tcl Shell
  8232. :return: None
  8233. """
  8234. self.app.log.debug("open_gcode()")
  8235. # How the object should be initialized
  8236. def obj_init(job_obj, app_obj_):
  8237. """
  8238. :param job_obj: the resulting object
  8239. :type app_obj_: App
  8240. """
  8241. assert isinstance(app_obj_, App), \
  8242. "Initializer expected App, got %s" % type(app_obj_)
  8243. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8244. try:
  8245. f = open(filename)
  8246. gcode = f.read()
  8247. f.close()
  8248. except IOError:
  8249. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8250. return "fail"
  8251. job_obj.gcode = gcode
  8252. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8253. if gcode_ret == "fail":
  8254. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8255. return "fail"
  8256. job_obj.create_geometry()
  8257. with self.app.proc_container.new(_("Opening G-Code.")):
  8258. # Object name
  8259. name = outname or filename.split('/')[-1].split('\\')[-1]
  8260. # New object creation and file processing
  8261. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8262. if ret_val == 'fail':
  8263. if from_tcl:
  8264. filename = self.defaults['global_tcl_path'] + '/' + name
  8265. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8266. if ret_val == 'fail':
  8267. self.inform.emit('[ERROR_NOTCL] %s' %
  8268. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8269. "Try to load it from File menu.\n "
  8270. "Attempting to create a FlatCAM CNCJob Object from "
  8271. "G-Code file failed during processing"))
  8272. return "fail"
  8273. # Register recent file
  8274. self.app.file_opened.emit("cncjob", filename)
  8275. # appGUI feedback
  8276. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8277. def open_hpgl2(self, filename, outname=None):
  8278. """
  8279. Opens a HPGL2 file, parses it and creates a new object for
  8280. it in the program. Thread-safe.
  8281. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8282. :param filename: HPGL2 file filename
  8283. :return: None
  8284. """
  8285. filename = filename
  8286. # How the object should be initialized
  8287. def obj_init(geo_obj, app_obj):
  8288. assert isinstance(geo_obj, GeometryObject), \
  8289. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8290. # Opening the file happens here
  8291. obj = HPGL2(self)
  8292. try:
  8293. HPGL2.parse_file(obj, filename)
  8294. except IOError:
  8295. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8296. return "fail"
  8297. except ParseError as err:
  8298. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8299. app_obj.log.error(str(err))
  8300. return "fail"
  8301. except Exception as e:
  8302. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8303. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8304. msg += traceback.format_exc()
  8305. app_obj.inform.emit(msg)
  8306. return "fail"
  8307. geo_obj.multigeo = True
  8308. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8309. geo_obj.tools = deepcopy(obj.tools)
  8310. geo_obj.source_file = deepcopy(obj.source_file)
  8311. del obj
  8312. if not geo_obj.solid_geometry:
  8313. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8314. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8315. return "fail"
  8316. self.app.log.debug("open_hpgl2()")
  8317. with self.app.proc_container.new(_("Opening HPGL2")):
  8318. # Object name
  8319. name = outname or filename.split('/')[-1].split('\\')[-1]
  8320. # # ## Object creation # ##
  8321. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8322. if ret == 'fail':
  8323. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8324. return 'fail'
  8325. # Register recent file
  8326. self.app.file_opened.emit("geometry", filename)
  8327. # appGUI feedback
  8328. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8329. def open_script(self, filename, outname=None, silent=False):
  8330. """
  8331. Opens a Script file, parses it and creates a new object for
  8332. it in the program. Thread-safe.
  8333. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8334. :param filename: Script file filename
  8335. :param silent: If True there will be no messages printed to StatusBar
  8336. :return: None
  8337. """
  8338. def obj_init(script_obj, app_obj):
  8339. assert isinstance(script_obj, ScriptObject), \
  8340. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8341. if silent is False:
  8342. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8343. try:
  8344. script_obj.parse_file(filename)
  8345. except IOError:
  8346. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8347. return "fail"
  8348. except ParseError as err:
  8349. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8350. app_obj.log.error(str(err))
  8351. return "fail"
  8352. except Exception as e:
  8353. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8354. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8355. msg += traceback.format_exc()
  8356. app_obj.inform.emit(msg)
  8357. return "fail"
  8358. self.app.log.debug("open_script()")
  8359. with self.app.proc_container.new(_("Opening TCL Script...")):
  8360. # Object name
  8361. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8362. # Object creation
  8363. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8364. if ret_val == 'fail':
  8365. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8366. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8367. if ret_val == 'fail':
  8368. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8369. return 'fail'
  8370. # Register recent file
  8371. self.app.file_opened.emit("script", filename)
  8372. # appGUI feedback
  8373. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8374. def open_config_file(self, filename, run_from_arg=None):
  8375. """
  8376. Loads a config file from the specified file.
  8377. :param filename: Name of the file from which to load.
  8378. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8379. :return: None
  8380. """
  8381. self.app.log.debug("Opening config file: " + filename)
  8382. if run_from_arg:
  8383. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8384. "Canvas initialization finished in"),
  8385. '%.2f' % self.app.used_time,
  8386. _("Opening FlatCAM Config file.")),
  8387. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8388. color=QtGui.QColor("gray"))
  8389. # # add the tab if it was closed
  8390. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8391. # # first clear previous text in text editor (if any)
  8392. # self.ui.text_editor_tab.code_editor.clear()
  8393. #
  8394. # # Switch plot_area to CNCJob tab
  8395. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8396. # close the Code editor if already open
  8397. if self.app.toggle_codeeditor:
  8398. self.app.on_toggle_code_editor()
  8399. self.app.on_toggle_code_editor()
  8400. try:
  8401. if filename:
  8402. f = QtCore.QFile(filename)
  8403. if f.open(QtCore.QIODevice.ReadOnly):
  8404. stream = QtCore.QTextStream(f)
  8405. code_edited = stream.readAll()
  8406. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8407. f.close()
  8408. except IOError:
  8409. self.app.log.error("Failed to open config file: %s" % filename)
  8410. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8411. return
  8412. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8413. """
  8414. Loads a project from the specified file.
  8415. 1) Loads and parses file
  8416. 2) Registers the file as recently opened.
  8417. 3) Calls on_file_new()
  8418. 4) Updates options
  8419. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8420. 6) Calls plot_all() if plot=True
  8421. :param filename: Name of the file from which to load.
  8422. :param run_from_arg: True if run for arguments
  8423. :param plot: If True plot all objects in the project
  8424. :param cli: Run from command line
  8425. :param from_tcl: True if run from Tcl Sehll
  8426. :return: None
  8427. """
  8428. self.app.log.debug("Opening project: " + filename)
  8429. # block autosaving while a project is loaded
  8430. self.app.block_autosave = True
  8431. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8432. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8433. if cli is None:
  8434. self.app.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8435. if run_from_arg:
  8436. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8437. "Canvas initialization finished in"),
  8438. '%.2f' % self.app.used_time,
  8439. _("Opening FlatCAM Project file.")),
  8440. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8441. color=QtGui.QColor("gray"))
  8442. # Open and parse an uncompressed Project file
  8443. try:
  8444. f = open(filename, 'r')
  8445. except IOError:
  8446. if from_tcl:
  8447. name = filename.split('/')[-1].split('\\')[-1]
  8448. filename = self.defaults['global_tcl_path'] + '/' + name
  8449. try:
  8450. f = open(filename, 'r')
  8451. except IOError:
  8452. self.app.log.error("Failed to open project file: %s" % filename)
  8453. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8454. return
  8455. else:
  8456. self.app.log.error("Failed to open project file: %s" % filename)
  8457. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8458. return
  8459. try:
  8460. d = json.load(f, object_hook=dict2obj)
  8461. except Exception as e:
  8462. self.app.log.error(
  8463. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8464. (filename, str(e)))
  8465. f.close()
  8466. # Open and parse a compressed Project file
  8467. try:
  8468. with lzma.open(filename) as f:
  8469. file_content = f.read().decode('utf-8')
  8470. d = json.loads(file_content, object_hook=dict2obj)
  8471. except Exception as e:
  8472. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8473. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8474. return
  8475. # Clear the current project
  8476. # # NOT THREAD SAFE # ##
  8477. if run_from_arg is True:
  8478. pass
  8479. elif cli is True:
  8480. self.app.delete_selection_shape()
  8481. else:
  8482. self.on_file_new()
  8483. # Project options
  8484. self.app.options.update(d['options'])
  8485. self.app.project_filename = filename
  8486. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8487. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8488. if cli is None:
  8489. self.app.set_screen_units(self.app.options["units"])
  8490. # Re create objects
  8491. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8492. for obj in d['objs']:
  8493. def obj_init(obj_inst, app_inst):
  8494. try:
  8495. obj_inst.from_dict(obj)
  8496. except Exception as erro:
  8497. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8498. return 'fail'
  8499. self.app.log.debug(
  8500. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8501. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8502. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8503. if cli is None:
  8504. self.app.set_ui_title(name="{} {}: {}".format(
  8505. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8506. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8507. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8508. self.app.should_we_save = False
  8509. self.app.file_opened.emit("project", filename)
  8510. # restore autosaving after a project was loaded
  8511. self.app.block_autosave = False
  8512. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8513. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8514. if cli is None:
  8515. self.app.set_ui_title(name=self.app.project_filename)
  8516. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8517. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8518. """
  8519. Saves the current project to the specified file.
  8520. :param filename: Name of the file in which to save.
  8521. :type filename: str
  8522. :param quit_action: if the project saving will be followed by an app quit; boolean
  8523. :param silent: if True will not display status messages
  8524. :param from_tcl True is run from Tcl Shell
  8525. :return: None
  8526. """
  8527. self.app.log.debug("save_project()")
  8528. self.app.save_in_progress = True
  8529. if from_tcl:
  8530. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8531. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8532. # Capture the latest changes
  8533. # Current object
  8534. try:
  8535. current_object = self.app.collection.get_active()
  8536. if current_object:
  8537. current_object.read_form()
  8538. except Exception as e:
  8539. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8540. # Serialize the whole project
  8541. d = {
  8542. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8543. "options": self.app.options,
  8544. "version": self.app.version
  8545. }
  8546. if self.defaults["global_save_compressed"] is True:
  8547. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8548. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8549. # # Write
  8550. f.write(g)
  8551. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8552. else:
  8553. # Open file
  8554. try:
  8555. f = open(filename, 'w')
  8556. except IOError:
  8557. self.app.log.error("Failed to open file for saving: %s", filename)
  8558. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8559. return
  8560. # Write
  8561. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8562. f.close()
  8563. # verification of the saved project
  8564. # Open and parse
  8565. try:
  8566. saved_f = open(filename, 'r')
  8567. except IOError:
  8568. if silent is False:
  8569. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8570. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8571. return
  8572. try:
  8573. saved_d = json.load(saved_f, object_hook=dict2obj)
  8574. except Exception:
  8575. if silent is False:
  8576. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8577. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8578. f.close()
  8579. return
  8580. saved_f.close()
  8581. if silent is False:
  8582. if 'version' in saved_d:
  8583. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8584. else:
  8585. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8586. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8587. tb_settings = QSettings("Open Source", "FlatCAM")
  8588. lock_state = self.app.ui.lock_action.isChecked()
  8589. tb_settings.setValue('toolbar_lock', lock_state)
  8590. # This will write the setting to the platform specific storage.
  8591. del tb_settings
  8592. # if quit:
  8593. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8594. # t.start()
  8595. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8596. def save_source_file(self, obj_name, filename):
  8597. """
  8598. Exports a FlatCAM Object to an Gerber/Excellon file.
  8599. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8600. :param filename: Path to the Gerber file to save to.
  8601. :return:
  8602. """
  8603. if filename is None:
  8604. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8605. is not None else self.defaults["global_last_folder"]
  8606. self.app.log.debug("save source file()")
  8607. obj = self.app.collection.get_by_name(obj_name)
  8608. file_string = StringIO(obj.source_file)
  8609. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8610. if file_string.getvalue() == '':
  8611. self.inform.emit('[ERROR_NOTCL] %s' %
  8612. _("Save cancelled because source file is empty. Try to export the file."))
  8613. return 'fail'
  8614. try:
  8615. with open(filename, 'w') as file:
  8616. file.writelines('G04*\n')
  8617. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8618. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8619. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8620. file.writelines('G04 Created on : %s*\n' % time_string)
  8621. for line in file_string:
  8622. file.writelines(line)
  8623. except PermissionError:
  8624. self.inform.emit('[WARNING] %s' %
  8625. _("Permission denied, saving not possible.\n"
  8626. "Most likely another app is holding the file open and not accessible."))
  8627. return 'fail'
  8628. def on_file_savedefaults(self):
  8629. """
  8630. Callback for menu item File->Save Defaults. Saves application default options
  8631. ``self.defaults`` to current_defaults.FlatConfig.
  8632. :return: None
  8633. """
  8634. self.app.preferencesUiManager.save_defaults()
  8635. # end of file