app_Main.py 476 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590
  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. log.info("FlatCAM Starting...")
  222. self.qapp = qapp
  223. # declare it here so there is a reference
  224. self.f_handlers = lambda: None
  225. # ############################################################################################################
  226. # ################# Setup the listening thread for another instance launching with args ######################
  227. # ############################################################################################################
  228. if sys.platform == 'win32' or sys.platform == 'linux':
  229. # make sure the thread is stored by using a self. otherwise it's garbage collected
  230. self.listen_th = QtCore.QThread()
  231. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  232. self.new_launch = ArgsThread()
  233. self.new_launch.open_signal[list].connect(self.on_startup_args)
  234. self.new_launch.moveToThread(self.listen_th)
  235. self.new_launch.start.emit()
  236. # ############################################################################################################
  237. # ########################################## OS-specific #####################################################
  238. # ############################################################################################################
  239. portable = False
  240. # Folder for user settings.
  241. if sys.platform == 'win32':
  242. if platform.architecture()[0] == '32bit':
  243. self.log.debug("Win32!")
  244. else:
  245. self.log.debug("Win64!")
  246. # #######################################################################################################
  247. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  248. # #######################################################################################################
  249. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r'):
  252. pass
  253. except FileNotFoundError:
  254. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r') as f:
  257. try:
  258. for line in f:
  259. param = str(line).replace('\n', '').rpartition('=')
  260. if param[0] == 'portable':
  261. try:
  262. portable = eval(param[2])
  263. except NameError:
  264. portable = False
  265. if param[0] == 'headless':
  266. if param[2].lower() == 'true':
  267. self.cmd_line_headless = 1
  268. else:
  269. self.cmd_line_headless = None
  270. except Exception as e:
  271. self.log.debug('App.__init__() -->%s' % str(e))
  272. return
  273. except FileNotFoundError as e:
  274. self.log.debug(str(e))
  275. pass
  276. if portable is False:
  277. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  278. else:
  279. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  280. self.os = 'windows'
  281. else: # Linux/Unix/MacOS
  282. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  283. self.os = 'unix'
  284. # ############################################################################################################
  285. # ################################# Setup folders and files ##################################################
  286. # ############################################################################################################
  287. if not os.path.exists(self.data_path):
  288. os.makedirs(self.data_path)
  289. self.log.debug('Created data folder: ' + self.data_path)
  290. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  291. self.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  292. self.preprocessorpaths = self.preprocessors_path()
  293. if not os.path.exists(self.preprocessorpaths):
  294. os.makedirs(self.preprocessorpaths)
  295. self.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  296. # create tools_db.FlatDB file if there is none
  297. db_path = self.tools_database_path()
  298. try:
  299. f = open(db_path)
  300. f.close()
  301. except IOError:
  302. self.log.debug('Creating empty tools_db.FlatDB')
  303. f = open(db_path, 'w')
  304. json.dump({}, f)
  305. f.close()
  306. # create current_defaults.FlatConfig file if there is none
  307. def_path = self.defaults_path()
  308. try:
  309. f = open(def_path)
  310. f.close()
  311. except IOError:
  312. self.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(def_path, 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # the factory defaults are written only once at the first launch of the application after installation
  317. FlatCAMDefaults.save_factory_defaults(self.factory_defaults_path(), self.version)
  318. # create a recent files json file if there is none
  319. rec_f_path = self.recent_files_path()
  320. try:
  321. f = open(rec_f_path)
  322. f.close()
  323. except IOError:
  324. self.log.debug('Creating empty recent.json')
  325. f = open(rec_f_path, 'w')
  326. json.dump([], f)
  327. f.close()
  328. # create a recent projects json file if there is none
  329. rec_proj_path = self.recent_projects_path()
  330. try:
  331. fp = open(rec_proj_path)
  332. fp.close()
  333. except IOError:
  334. self.log.debug('Creating empty recent_projects.json')
  335. fp = open(rec_proj_path, 'w')
  336. json.dump([], fp)
  337. fp.close()
  338. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  339. # This will fail under cx_freeze ...
  340. self.app_home = os.path.dirname(os.path.realpath(__file__))
  341. self.log.debug("Application path is " + self.app_home)
  342. self.log.debug("Started in " + os.getcwd())
  343. # cx_freeze workaround
  344. if os.path.isfile(self.app_home):
  345. self.app_home = os.path.dirname(self.app_home)
  346. os.chdir(self.app_home)
  347. # ############################################################################################################
  348. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  349. # ############################################################################################################
  350. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  351. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  352. if user_defaults:
  353. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  354. if self.defaults['units'] == 'MM':
  355. self.decimals = int(self.defaults['decimals_metric'])
  356. else:
  357. self.decimals = int(self.defaults['decimals_inch'])
  358. if self.defaults["global_gray_icons"] is False:
  359. self.resource_location = 'assets/resources'
  360. else:
  361. self.resource_location = 'assets/resources/dark_resources'
  362. self.current_units = self.defaults['units']
  363. # ###########################################################################################################
  364. # #################################### SETUP OBJECT CLASSES #################################################
  365. # ###########################################################################################################
  366. self.setup_obj_classes()
  367. # ###########################################################################################################
  368. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  369. # ###########################################################################################################
  370. self.pool = Pool()
  371. # ###########################################################################################################
  372. # ###################################### Clear GUI Settings - once at first start ###########################
  373. # ###########################################################################################################
  374. if self.defaults["first_run"] is True:
  375. # on first run clear the previous QSettings, therefore clearing the GUI settings
  376. qsettings = QSettings("Open Source", "FlatCAM")
  377. for key in qsettings.allKeys():
  378. qsettings.remove(key)
  379. # This will write the setting to the platform specific storage.
  380. del qsettings
  381. # ###########################################################################################################
  382. # ###################################### Setting the Splash Screen ##########################################
  383. # ###########################################################################################################
  384. splash_settings = QSettings("Open Source", "FlatCAM")
  385. if splash_settings.contains("splash_screen"):
  386. show_splash = splash_settings.value("splash_screen")
  387. else:
  388. splash_settings.setValue('splash_screen', 1)
  389. # This will write the setting to the platform specific storage.
  390. del splash_settings
  391. show_splash = 1
  392. if show_splash and self.cmd_line_headless != 1:
  393. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  394. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  395. # self.splash.setMask(splash_pix.mask())
  396. # move splashscreen to the current monitor
  397. desktop = QtWidgets.QApplication.desktop()
  398. screen = desktop.screenNumber(QtGui.QCursor.pos())
  399. current_screen_center = desktop.availableGeometry(screen).center()
  400. self.splash.move(current_screen_center - self.splash.rect().center())
  401. self.splash.show()
  402. self.splash.showMessage(_("The application is initializing ..."),
  403. alignment=Qt.AlignBottom | Qt.AlignLeft,
  404. color=QtGui.QColor("gray"))
  405. else:
  406. self.splash = None
  407. show_splash = 0
  408. # ###########################################################################################################
  409. # ######################################### Initialize GUI ##################################################
  410. # ###########################################################################################################
  411. # FlatCAM colors used in plotting
  412. self.FC_light_green = '#BBF268BF'
  413. self.FC_dark_green = '#006E20BF'
  414. self.FC_light_blue = '#a5a5ffbf'
  415. self.FC_dark_blue = '#0000ffbf'
  416. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  417. if theme_settings.contains("theme"):
  418. theme = theme_settings.value('theme', type=str)
  419. else:
  420. theme = 'white'
  421. if self.defaults["global_cursor_color_enabled"]:
  422. self.cursor_color_3D = self.defaults["global_cursor_color"]
  423. else:
  424. if theme == 'white':
  425. self.cursor_color_3D = 'black'
  426. else:
  427. self.cursor_color_3D = 'gray'
  428. # update the defaults dict with the setting in QSetting
  429. self.defaults['global_theme'] = theme
  430. self.ui = MainGUI(self)
  431. # set FlatCAM units in the Status bar
  432. self.set_screen_units(self.defaults['units'])
  433. # ###########################################################################################################
  434. # ########################################### AUTOSAVE SETUP ################################################
  435. # ###########################################################################################################
  436. self.block_autosave = False
  437. self.autosave_timer = QtCore.QTimer(self)
  438. self.save_project_auto_update()
  439. self.autosave_timer.timeout.connect(self.save_project_auto)
  440. # ###########################################################################################################
  441. # #################################### LOAD PREPROCESSORS ###################################################
  442. # ###########################################################################################################
  443. # ----------------------------------------- WARNING --------------------------------------------------------
  444. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  445. # That's because the number of preprocessors can vary and here the comboboxes are populated
  446. # -----------------------------------------------------------------------------------------------------------
  447. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  448. # the preprocessor file
  449. self.preprocessors = load_preprocessors(self)
  450. # make sure that always the 'default' preprocessor is the first item in the dictionary
  451. if 'default' in self.preprocessors.keys():
  452. new_ppp_dict = {}
  453. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  454. default_pp = self.preprocessors.pop('default')
  455. new_ppp_dict['default'] = default_pp
  456. # then add the rest of the keys
  457. for name, val_class in self.preprocessors.items():
  458. new_ppp_dict[name] = val_class
  459. # and now put back the ordered dict with 'default' key first
  460. self.preprocessors = new_ppp_dict
  461. # populate the Preprocessor ComboBoxes in the PREFERENCES
  462. for name in list(self.preprocessors.keys()):
  463. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  464. if name.partition('_')[0] == 'Paste':
  465. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  466. continue
  467. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  468. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  469. if name == 'hpgl':
  470. continue
  471. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  472. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  473. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  474. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  475. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  476. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  477. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  478. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  479. QtCore.Qt.ToolTipRole)
  480. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  481. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  482. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  483. QtCore.Qt.ToolTipRole)
  484. # ###########################################################################################################
  485. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  486. # ###########################################################################################################
  487. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  488. inform=self.inform)
  489. self.preferencesUiManager.defaults_write_form()
  490. # When the self.defaults dictionary changes will update the Preferences GUI forms
  491. self.defaults.set_change_callback(self.on_defaults_dict_change)
  492. # ###########################################################################################################
  493. # ##################################### FIRST RUN SECTION ###################################################
  494. # ################################ It's done only once after install #####################################
  495. # ###########################################################################################################
  496. if self.defaults["first_run"] is True:
  497. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  498. initial_lay = 'minimal'
  499. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  500. # Set the combobox in Preferences to the current layout
  501. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  502. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  503. # after the first run, this object should be False
  504. self.defaults["first_run"] = False
  505. self.preferencesUiManager.save_defaults(silent=True)
  506. # ###########################################################################################################
  507. # ############################################ Data #########################################################
  508. # ###########################################################################################################
  509. self.recent = []
  510. self.recent_projects = []
  511. self.clipboard = QtWidgets.QApplication.clipboard()
  512. self.project_filename = None
  513. self.toggle_units_ignore = False
  514. self.main_thread = QtWidgets.QApplication.instance().thread()
  515. # ###########################################################################################################
  516. # ########################################## LOAD LANGUAGES ################################################
  517. # ###########################################################################################################
  518. self.languages = fcTranslate.load_languages()
  519. for name in sorted(self.languages.values()):
  520. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  521. # ###########################################################################################################
  522. # ####################################### APPLY APP LANGUAGE ################################################
  523. # ###########################################################################################################
  524. ret_val = fcTranslate.apply_language('strings')
  525. if ret_val == "no language":
  526. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  527. self.log.debug("Could not find the Language files. The App strings are missing.")
  528. else:
  529. # make the current language the current selection on the language combobox
  530. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  531. self.log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  532. # ###########################################################################################################
  533. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  534. # ###########################################################################################################
  535. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  536. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  537. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  538. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  539. self.defaults.propagate_defaults()
  540. # ###########################################################################################################
  541. # ######################################## UPDATE THE OPTIONS ###############################################
  542. # ###########################################################################################################
  543. self.options = LoudDict()
  544. # -----------------------------------------------------------------------------------------------------------
  545. # Update the self.options from the self.defaults
  546. # The self.defaults holds the application defaults while the self.options holds the object defaults
  547. # -----------------------------------------------------------------------------------------------------------
  548. # Copy app defaults to project options
  549. for def_key, def_val in self.defaults.items():
  550. self.options[def_key] = deepcopy(def_val)
  551. self.preferencesUiManager.show_preferences_gui()
  552. # ### End of Data ####
  553. # ###########################################################################################################
  554. # #################################### SETUP OBJECT COLLECTION ##############################################
  555. # ###########################################################################################################
  556. self.collection = ObjectCollection(app=self)
  557. self.ui.project_tab_layout.addWidget(self.collection.view)
  558. self.app_obj = AppObject(app=self)
  559. # ### Adjust tabs width ## ##
  560. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  561. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  562. self.collection.view.setMinimumWidth(290)
  563. self.log.debug("Finished creating Object Collection.")
  564. # ###########################################################################################################
  565. # ######################################## SETUP Plot Area ##################################################
  566. # ###########################################################################################################
  567. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  568. if self.defaults["global_graphic_engine"] == '3D':
  569. self.is_legacy = False
  570. else:
  571. self.is_legacy = True
  572. # Event signals disconnect id holders
  573. self.mp = None
  574. self.mm = None
  575. self.mr = None
  576. self.mdc = None
  577. self.mp_zc = None
  578. self.kp = None
  579. # Matplotlib axis
  580. self.axes = None
  581. if show_splash:
  582. self.splash.showMessage(_("The application is initializing ...\n"
  583. "Canvas initialization started."),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. start_plot_time = time.time() # debug
  587. self.plotcanvas = None
  588. self.app_cursor = None
  589. self.hover_shapes = None
  590. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  591. # setup the PlotCanvas
  592. self.on_plotcanvas_setup()
  593. end_plot_time = time.time()
  594. self.used_time = end_plot_time - start_plot_time
  595. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  596. if show_splash:
  597. self.splash.showMessage('%s: %ssec' % (_("The application is initializing ...\n"
  598. "Canvas initialization started.\n"
  599. "Canvas initialization finished in"), '%.2f' % self.used_time),
  600. alignment=Qt.AlignBottom | Qt.AlignLeft,
  601. color=QtGui.QColor("gray"))
  602. self.ui.splitter.setStretchFactor(1, 2)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ############################################
  614. # ###########################################################################################################
  615. # self.activity_view = FlatCAMActivityView(app=self)
  616. # self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  618. # ###########################################################################################################
  619. # ########################################## Other setups ###################################################
  620. # ###########################################################################################################
  621. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  622. # depending on from where those tools are called different actions can be done
  623. self.call_source = 'app'
  624. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  625. self.tool_tab_locked = False
  626. # decide if to show or hide the Notebook side of the screen at startup
  627. if self.defaults["global_project_at_startup"] is True:
  628. self.ui.splitter.setSizes([1, 1])
  629. else:
  630. self.ui.splitter.setSizes([0, 1])
  631. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  632. self.setup_default_properties_tab()
  633. # ###########################################################################################################
  634. # ####################################### Auto-complete KEYWORDS ############################################
  635. # ###########################################################################################################
  636. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  637. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  638. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  639. 'export_exc',
  640. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  641. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  642. 'interiors', 'isolate', 'join_excellon',
  643. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  644. 'mirror', 'ncc',
  645. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  646. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  647. 'options', 'origin',
  648. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  649. 'save', 'save_project',
  650. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  651. 'skew', 'subtract_poly', 'subtract_rectangle',
  652. 'version', 'write_gcode'
  653. ]
  654. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  655. 'Paste_1',
  656. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  657. 'Toolchange_manual', 'True', 'Users',
  658. 'all', 'auto', 'axis',
  659. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  660. 'contour', 'default',
  661. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  662. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  663. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  664. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  665. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  666. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  667. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  668. 'spacing_columns',
  669. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  670. 'toolchange_xy', 'toolchangez', 'travelz',
  671. 'tooldia', 'use_threads', 'value',
  672. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  673. ]
  674. self.tcl_keywords = [
  675. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  676. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  677. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  678. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  679. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  680. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  681. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  682. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  683. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  684. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  685. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  686. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  687. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  688. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  689. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  690. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  691. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  692. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  693. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  694. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  695. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  696. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  697. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  698. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  699. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  700. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  701. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  702. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  703. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  704. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  705. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  706. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  707. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  708. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  709. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  710. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  711. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  712. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  713. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  714. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  715. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  716. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  717. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  718. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  719. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  720. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  721. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  722. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  723. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  724. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  725. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  726. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  727. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  728. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  729. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  730. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  731. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  732. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  733. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  734. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  735. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  736. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  737. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  738. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  739. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  740. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  741. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  742. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  743. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  744. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  745. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  746. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  747. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  748. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  749. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  750. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  751. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  752. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  753. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  754. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  755. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  756. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  757. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  758. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  759. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  760. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  761. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  762. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  763. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  764. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  765. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  766. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  767. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  768. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  769. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  770. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  771. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  772. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  773. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  774. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  775. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  776. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  777. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  778. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  779. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  780. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  781. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  782. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  783. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  784. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  785. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  786. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  787. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  788. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  789. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  790. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  791. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  792. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  793. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  794. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  795. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  796. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  797. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  798. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  799. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  800. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  801. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  802. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  803. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  804. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  805. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  806. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  807. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  808. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  809. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  810. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  811. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  812. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  813. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  814. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  815. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  816. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  817. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  818. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  819. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  820. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  821. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  822. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  823. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  824. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  825. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  826. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  827. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  828. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  829. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  830. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  831. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  832. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  833. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  834. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  835. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  836. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  837. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  838. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  839. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  840. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  841. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  842. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  843. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  844. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  845. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  846. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  847. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  848. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  849. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  850. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  851. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  852. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  853. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  854. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  855. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  856. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  857. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  858. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  859. ]
  860. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  861. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  862. # ###########################################################################################################
  863. # ########################################## Tools and Plugins ##############################################
  864. # ###########################################################################################################
  865. self.shell = None
  866. self.dblsidedtool = None
  867. self.distance_tool = None
  868. self.distance_min_tool = None
  869. self.panelize_tool = None
  870. self.film_tool = None
  871. self.paste_tool = None
  872. self.calculator_tool = None
  873. self.rules_tool = None
  874. self.sub_tool = None
  875. self.move_tool = None
  876. self.cutout_tool = None
  877. self.ncclear_tool = None
  878. self.paint_tool = None
  879. self.isolation_tool = None
  880. self.drilling_tool = None
  881. self.optimal_tool = None
  882. self.transform_tool = None
  883. self.properties_tool = None
  884. self.pdf_tool = None
  885. self.image_tool = None
  886. self.pcb_wizard_tool = None
  887. self.cal_exc_tool = None
  888. self.qrcode_tool = None
  889. self.copper_thieving_tool = None
  890. self.fiducial_tool = None
  891. self.edrills_tool = None
  892. self.align_objects_tool = None
  893. self.punch_tool = None
  894. self.invert_tool = None
  895. self.corners_tool = None
  896. self.etch_tool = None
  897. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  898. try:
  899. self.install_tools()
  900. except AttributeError as e:
  901. self.log.debug("App.__init__() install_tools() --> %s" % str(e))
  902. # ###########################################################################################################
  903. # ######################################### BookMarks Manager ###############################################
  904. # ###########################################################################################################
  905. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  906. self.install_bookmarks()
  907. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  908. # ###########################################################################################################
  909. # ########################################### Tools Database ################################################
  910. # ###########################################################################################################
  911. self.tools_db_tab = None
  912. # ### System Font Parsing ###
  913. # self.f_parse = ParseFont(self)
  914. # self.parse_system_fonts()
  915. # ###########################################################################################################
  916. # ############################################## Shell SETUP ################################################
  917. # ###########################################################################################################
  918. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  919. if self.defaults["global_shell_at_startup"]:
  920. self.ui.shell_dock.show()
  921. else:
  922. self.ui.shell_dock.hide()
  923. # ###########################################################################################################
  924. # ######################################### Check for updates ###############################################
  925. # ###########################################################################################################
  926. # Separate thread (Not worker)
  927. # Check for updates on startup but only if the user consent and the app is not in Beta version
  928. if (self.beta is False or self.beta is None) and \
  929. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  930. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  931. # self.thr2 = QtCore.QThread()
  932. self.worker_task.emit({'fcn': self.version_check,
  933. 'params': []})
  934. # self.thr2.start(QtCore.QThread.LowPriority)
  935. # ###########################################################################################################
  936. # ##################################### Register files with FlatCAM; #######################################
  937. # ################################### It works only for Windows for now ####################################
  938. # ###########################################################################################################
  939. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  940. self.on_register_files()
  941. # ###########################################################################################################
  942. # ######################################## Variables for global usage #######################################
  943. # ###########################################################################################################
  944. # hold the App units
  945. self.units = 'MM'
  946. # coordinates for relative position display
  947. self.rel_point1 = (0, 0)
  948. self.rel_point2 = (0, 0)
  949. # variable to store coordinates
  950. self.pos = (0, 0)
  951. self.pos_canvas = (0, 0)
  952. self.pos_jump = (0, 0)
  953. # variable to store mouse coordinates
  954. self.mouse = [0, 0]
  955. # variable to store the delta positions on cavnas
  956. self.dx = 0
  957. self.dy = 0
  958. # decide if we have a double click or single click
  959. self.doubleclick = False
  960. # store here the is_dragging value
  961. self.event_is_dragging = False
  962. # variable to store if a command is active (then the var is not None) and which one it is
  963. self.command_active = None
  964. # variable to store the status of moving selection action
  965. # None value means that it's not an selection action
  966. # True value = a selection from left to right
  967. # False value = a selection from right to left
  968. self.selection_type = None
  969. # List to store the objects that are currently loaded in FlatCAM
  970. # This list is updated on each object creation or object delete
  971. self.all_objects_list = []
  972. self.objects_under_the_click_list = []
  973. # List to store the objects that are selected
  974. self.sel_objects_list = []
  975. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  976. self.key_modifiers = None
  977. # Variable to store the status of the code editor
  978. self.toggle_codeeditor = False
  979. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  980. self.click_noproject = False
  981. self.cursor = None
  982. # Variable to store the GCODE that was edited
  983. self.gcode_edited = ""
  984. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  985. self.old_state_of_tools_toolbar = False
  986. self.text_editor_tab = None
  987. # reference for the self.ui.code_editor
  988. self.reference_code_editor = None
  989. self.script_code = ''
  990. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  991. self.tools_db_changed_flag = False
  992. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  993. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  994. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  995. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  996. 'tsm']
  997. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  998. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  999. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1000. 'sbp', 'tap', 'xpi']
  1001. self.svg_list = ['svg']
  1002. self.dxf_list = ['dxf']
  1003. self.pdf_list = ['pdf']
  1004. self.prj_list = ['flatprj']
  1005. self.conf_list = ['flatconfig']
  1006. # last used filters
  1007. self.last_op_gerber_filter = None
  1008. self.last_op_excellon_filter = None
  1009. self.last_op_gcode_filter = None
  1010. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1011. # flag for polygons not cleared
  1012. self.poly_not_cleared = False
  1013. # VisPy visuals
  1014. self.isHovering = False
  1015. self.notHovering = True
  1016. # Window geometry
  1017. self.x_pos = None
  1018. self.y_pos = None
  1019. self.width = None
  1020. self.height = None
  1021. # when True, the app has to return from any thread
  1022. self.abort_flag = False
  1023. # set the value used in the Windows Title
  1024. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1025. # this holds a widget that is installed in the Plot Area when View Source option is used
  1026. self.source_editor_tab = None
  1027. self.pagesize = {}
  1028. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1029. # VisPy visuals
  1030. if self.is_legacy is False:
  1031. try:
  1032. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1033. except AttributeError:
  1034. self.tool_shapes = None
  1035. else:
  1036. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1037. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1038. # used in the delayed shutdown self.start_delayed_quit() method
  1039. self.save_timer = None
  1040. # ###########################################################################################################
  1041. # ################################## ADDING FlatCAM EDITORS section #########################################
  1042. # ###########################################################################################################
  1043. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1044. # at the first launch of the App , the editors will not be functional.
  1045. try:
  1046. self.geo_editor = AppGeoEditor(self)
  1047. except Exception as es:
  1048. self.log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1049. try:
  1050. self.exc_editor = AppExcEditor(self)
  1051. except Exception as es:
  1052. self.log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1053. try:
  1054. self.grb_editor = AppGerberEditor(self)
  1055. except Exception as es:
  1056. self.log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1057. try:
  1058. self.gcode_editor = AppGCodeEditor(self)
  1059. except Exception as es:
  1060. self.log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1061. self.log.debug("Finished adding FlatCAM Editor's.")
  1062. self.ui.set_ui_title(name=_("New Project - Not saved"))
  1063. current_platform = platform.architecture()[0]
  1064. if current_platform != '64bit':
  1065. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1066. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1067. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1068. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1069. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1070. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1071. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1072. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1073. # ###########################################################################################################
  1074. # ########################################### EXCLUSION AREAS ###############################################
  1075. # ###########################################################################################################
  1076. self.exc_areas = ExclusionAreas(app=self)
  1077. # ###########################################################################################################
  1078. # ###########################################################################################################
  1079. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1080. # ###########################################################################################################
  1081. # ###########################################################################################################
  1082. self.f_handlers = MenuFileHandlers(app=self)
  1083. # this is calculated in the class above (somehow?)
  1084. self.defaults["root_folder_path"] = self.app_home
  1085. # ###########################################################################################################
  1086. # ############################################### SYS TRAY ##################################################
  1087. # ###########################################################################################################
  1088. if self.defaults["global_systray_icon"]:
  1089. self.parent_w = QtWidgets.QWidget()
  1090. if self.cmd_line_headless == 1:
  1091. self.trayIcon = FlatCAMSystemTray(app=self,
  1092. icon=QtGui.QIcon(self.resource_location +
  1093. '/flatcam_icon32_green.png'),
  1094. headless=True,
  1095. parent=self.parent_w)
  1096. else:
  1097. self.trayIcon = FlatCAMSystemTray(app=self,
  1098. icon=QtGui.QIcon(self.resource_location +
  1099. '/flatcam_icon32_green.png'),
  1100. parent=self.parent_w)
  1101. # ###########################################################################################################
  1102. # ############################################ SETUP RECENT ITEMS ###########################################
  1103. # ###########################################################################################################
  1104. self.setup_recent_items()
  1105. # ###########################################################################################################
  1106. # ###########################################################################################################
  1107. # ############################################# Signal handling #############################################
  1108. # ###########################################################################################################
  1109. # ###########################################################################################################
  1110. # ########################################## Custom signals ################################################
  1111. # signal for displaying messages in status bar
  1112. self.inform[str].connect(self.info)
  1113. self.inform[str, bool].connect(self.info)
  1114. # signal for displaying messages in the shell
  1115. self.inform_shell[str].connect(self.info_shell)
  1116. self.inform_shell[str, bool].connect(self.info_shell)
  1117. # signal to be called when the app is quiting
  1118. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1119. self.message.connect(lambda: message_dialog(parent=self.ui))
  1120. # self.progress.connect(self.set_progress_bar)
  1121. # signals emitted when file state change
  1122. self.file_opened.connect(self.register_recent)
  1123. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1124. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1125. # when the defaults dictionary values change
  1126. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1127. # ########################################## Standard signals ###############################################
  1128. # ### Menu
  1129. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1130. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1131. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1132. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1133. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1134. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1135. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1136. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1137. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1138. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1139. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1140. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1141. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1142. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1143. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1144. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1145. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1146. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1147. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1148. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1149. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1150. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1151. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1152. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1153. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1154. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1155. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1156. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1157. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1158. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1159. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1160. self.ui.menufile_exit.triggered.connect(self.final_save)
  1161. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1162. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1163. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1164. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1165. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1166. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1167. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1168. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1169. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1170. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1171. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1172. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1173. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1174. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1175. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1176. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1177. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1178. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1179. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1180. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1181. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1182. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1183. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1184. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1185. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1186. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1187. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1188. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1189. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1190. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1191. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1192. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1193. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1194. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1195. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1196. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1197. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1198. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1199. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1200. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1201. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1202. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1203. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1204. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1205. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1206. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1207. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1208. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1209. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1210. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1211. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1212. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1213. self.ui.menuhelp_readme.triggered.connect(self.on_howto)
  1214. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1215. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1216. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1217. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1218. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1219. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1220. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1221. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1222. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1223. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1224. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1225. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1226. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1227. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1228. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1229. # ToolBar signals
  1230. self.connect_toolbar_signals(ui=self.ui)
  1231. # Context Menu
  1232. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1233. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1234. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1235. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1236. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1237. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1238. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1239. self.ui.clearplot.triggered.connect(self.clear_plots)
  1240. self.ui.replot.triggered.connect(self.plot_all)
  1241. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1242. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1243. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1244. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1245. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1246. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1247. # Project Context Menu -> Color Setting
  1248. for act in self.ui.menuprojectcolor.actions():
  1249. act.triggered.connect(self.on_set_color_action_triggered)
  1250. # Notebook tab clicking
  1251. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1252. # ###########################################################################################################
  1253. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1254. # ###########################################################################################################
  1255. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1256. lambda: self.on_toggle_units(no_pref=False))
  1257. # ##################################### Workspace Setting Signals ###########################################
  1258. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1259. self.on_workspace_modified)
  1260. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1261. self.on_workspace_modified
  1262. )
  1263. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1264. # ###########################################################################################################
  1265. # ######################################## GUI SETTINGS SIGNALS #############################################
  1266. # ###########################################################################################################
  1267. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1268. # ######################################## Tools related signals ############################################
  1269. # portability changed signal
  1270. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1271. # Object list
  1272. self.object_status_changed.connect(self.collection.on_collection_updated)
  1273. # when there are arguments at application startup this get launched
  1274. self.args_at_startup[list].connect(self.on_startup_args)
  1275. # ###########################################################################################################
  1276. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1277. # ###########################################################################################################
  1278. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1279. lambda: self.restore_extensions(ext_type='excellon'))
  1280. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1281. lambda: self.restore_extensions(ext_type='gcode'))
  1282. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1283. lambda: self.restore_extensions(ext_type='gerber'))
  1284. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1285. lambda: self.delete_all_extensions(ext_type='excellon'))
  1286. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1287. lambda: self.delete_all_extensions(ext_type='gcode'))
  1288. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1289. lambda: self.delete_all_extensions(ext_type='gerber'))
  1290. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1291. lambda: self.add_extension(ext_type='excellon'))
  1292. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1293. lambda: self.add_extension(ext_type='gcode'))
  1294. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1295. lambda: self.add_extension(ext_type='gerber'))
  1296. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1297. lambda: self.del_extension(ext_type='excellon'))
  1298. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1299. lambda: self.del_extension(ext_type='gcode'))
  1300. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1301. lambda: self.del_extension(ext_type='gerber'))
  1302. # connect the 'Apply' buttons from the Preferences/File Associations
  1303. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1304. lambda: self.on_register_files(obj_type='excellon'))
  1305. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1306. lambda: self.on_register_files(obj_type='gcode'))
  1307. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1308. lambda: self.on_register_files(obj_type='gerber'))
  1309. # ###########################################################################################################
  1310. # ########################################### KEYWORDS SIGNALS ##############################################
  1311. # ###########################################################################################################
  1312. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1313. lambda: self.restore_extensions(ext_type='keyword'))
  1314. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1315. lambda: self.delete_all_extensions(ext_type='keyword'))
  1316. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1317. lambda: self.add_extension(ext_type='keyword'))
  1318. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1319. lambda: self.del_extension(ext_type='keyword'))
  1320. # ###########################################################################################################
  1321. # ########################################### GUI SIGNALS ###################################################
  1322. # ###########################################################################################################
  1323. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1324. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1325. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1326. # ###########################################################################################################
  1327. # ####################################### VARIOUS SIGNALS ###################################################
  1328. # ###########################################################################################################
  1329. # connect the abort_all_tasks related slots to the related signals
  1330. self.proc_container.idle_flag.connect(self.app_is_idle)
  1331. # signal emitted when a tab is closed in the Plot Area
  1332. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1333. # signal to close the application
  1334. self.close_app_signal.connect(self.kill_app)
  1335. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1336. # ###########################################################################################################
  1337. # ###########################################################################################################
  1338. # ###########################################################################################################
  1339. self.log.debug("Finished connecting Signals.")
  1340. # ###########################################################################################################
  1341. # ##################################### Finished the CONSTRUCTOR ############################################
  1342. # ###########################################################################################################
  1343. self.log.debug("END of constructor. Releasing control.")
  1344. # ###########################################################################################################
  1345. # ########################################## SHOW GUI #######################################################
  1346. # ###########################################################################################################
  1347. # if the app is not started as headless, show it
  1348. if self.cmd_line_headless != 1:
  1349. if show_splash:
  1350. # finish the splash
  1351. self.splash.finish(self.ui)
  1352. mgui_settings = QSettings("Open Source", "FlatCAM")
  1353. if mgui_settings.contains("maximized_gui"):
  1354. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1355. if maximized_ui is True:
  1356. self.ui.showMaximized()
  1357. else:
  1358. self.ui.show()
  1359. else:
  1360. self.ui.show()
  1361. if self.defaults["global_systray_icon"]:
  1362. self.trayIcon.show()
  1363. else:
  1364. log.warning("******************* RUNNING HEADLESS *******************")
  1365. # ###########################################################################################################
  1366. # ######################################## START-UP ARGUMENTS ###############################################
  1367. # ###########################################################################################################
  1368. # test if the program was started with a script as parameter
  1369. if self.cmd_line_shellvar:
  1370. try:
  1371. cnt = 0
  1372. command_tcl = 0
  1373. for i in self.cmd_line_shellvar.split(','):
  1374. if i is not None:
  1375. # noinspection PyBroadException
  1376. try:
  1377. command_tcl = eval(i)
  1378. except Exception:
  1379. command_tcl = i
  1380. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1381. cnt += 1
  1382. # if there are Windows paths then replace the path separator with a Unix like one
  1383. if sys.platform == 'win32':
  1384. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1385. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1386. except Exception as ext:
  1387. print("ERROR: ", ext)
  1388. sys.exit(2)
  1389. if self.cmd_line_shellfile:
  1390. if self.cmd_line_headless != 1:
  1391. if self.ui.shell_dock.isHidden():
  1392. self.ui.shell_dock.show()
  1393. try:
  1394. with open(self.cmd_line_shellfile, "r") as myfile:
  1395. # if show_splash:
  1396. # self.splash.showMessage('%s: %ssec\n%s' % (
  1397. # _("Canvas initialization started.\n"
  1398. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1399. # _("Executing Tcl Script ...")),
  1400. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1401. # color=QtGui.QColor("gray"))
  1402. cmd_line_shellfile_text = myfile.read()
  1403. if self.cmd_line_headless != 1:
  1404. self.shell.exec_command(cmd_line_shellfile_text)
  1405. else:
  1406. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1407. except Exception as ext:
  1408. print("ERROR: ", ext)
  1409. sys.exit(2)
  1410. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1411. # the path/file_name must be enclosed in quotes if it contain spaces
  1412. if App.args:
  1413. self.args_at_startup.emit(App.args)
  1414. if self.defaults.old_defaults_found is True:
  1415. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1416. "Please reboot the application to update."))
  1417. self.defaults.old_defaults_found = False
  1418. # ######################################### INIT FINISHED #######################################################
  1419. # #################################################################################################################
  1420. # #################################################################################################################
  1421. # #################################################################################################################
  1422. # #################################################################################################################
  1423. # #################################################################################################################
  1424. @staticmethod
  1425. def copy_and_overwrite(from_path, to_path):
  1426. """
  1427. From here:
  1428. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1429. :param from_path: source path
  1430. :param to_path: destination path
  1431. :return: None
  1432. """
  1433. if os.path.exists(to_path):
  1434. shutil.rmtree(to_path)
  1435. try:
  1436. shutil.copytree(from_path, to_path)
  1437. except FileNotFoundError:
  1438. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1439. shutil.copytree(from_new_path, to_path)
  1440. def on_startup_args(self, args, silent=False):
  1441. """
  1442. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1443. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1444. :param args: a list containing the application args at startup
  1445. :return: None
  1446. """
  1447. if args is not None:
  1448. args_to_process = args
  1449. else:
  1450. args_to_process = App.args
  1451. self.log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1452. for argument in args_to_process:
  1453. if '.FlatPrj'.lower() in argument.lower():
  1454. try:
  1455. project_name = str(argument)
  1456. if project_name == "":
  1457. if silent is False:
  1458. self.inform.emit(_("Cancelled."))
  1459. else:
  1460. # self.open_project(project_name)
  1461. run_from_arg = True
  1462. # self.worker_task.emit({'fcn': self.open_project,
  1463. # 'params': [project_name, run_from_arg]})
  1464. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1465. except Exception as e:
  1466. self.log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1467. elif '.FlatConfig'.lower() in argument.lower():
  1468. try:
  1469. file_name = str(argument)
  1470. if file_name == "":
  1471. if silent is False:
  1472. self.inform.emit(_("Open Config file failed."))
  1473. else:
  1474. run_from_arg = True
  1475. # self.worker_task.emit({'fcn': self.open_config_file,
  1476. # 'params': [file_name, run_from_arg]})
  1477. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1478. except Exception as e:
  1479. self.log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1480. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1481. try:
  1482. file_name = str(argument)
  1483. if file_name == "":
  1484. if silent is False:
  1485. self.inform.emit(_("Open Script file failed."))
  1486. else:
  1487. if silent is False:
  1488. self.on_fileopenscript(name=file_name)
  1489. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1490. self.on_filerunscript(name=file_name)
  1491. except Exception as e:
  1492. self.log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1493. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1494. self.log.debug("App.on_startup_args() --> Quit event.")
  1495. sys.exit()
  1496. elif 'save'.lower() in argument.lower():
  1497. self.log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1498. self.preferencesUiManager.save_defaults()
  1499. else:
  1500. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1501. proc_arg = argument.lower()
  1502. for ext in exc_list:
  1503. proc_ext = ext.replace(' ', '')
  1504. proc_ext = '.%s' % proc_ext
  1505. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1506. file_name = str(argument)
  1507. if file_name == "":
  1508. if silent is False:
  1509. self.inform.emit(_("Open Excellon file failed."))
  1510. else:
  1511. self.on_fileopenexcellon(name=file_name, signal=None)
  1512. return
  1513. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1514. for ext in gco_list:
  1515. proc_ext = ext.replace(' ', '')
  1516. proc_ext = '.%s' % proc_ext
  1517. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1518. file_name = str(argument)
  1519. if file_name == "":
  1520. if silent is False:
  1521. self.inform.emit(_("Open GCode file failed."))
  1522. else:
  1523. self.on_fileopengcode(name=file_name, signal=None)
  1524. return
  1525. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1526. for ext in grb_list:
  1527. proc_ext = ext.replace(' ', '')
  1528. proc_ext = '.%s' % proc_ext
  1529. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1530. file_name = str(argument)
  1531. if file_name == "":
  1532. if silent is False:
  1533. self.inform.emit(_("Open Gerber file failed."))
  1534. else:
  1535. self.on_fileopengerber(name=file_name, signal=None)
  1536. return
  1537. # if it reached here without already returning then the app was registered with a file that it does not
  1538. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1539. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1540. # for arg in args_to_process:
  1541. # if 'FlatCAM.exe' in arg:
  1542. # continue
  1543. # else:
  1544. # sys.exit(2)
  1545. def tools_database_path(self):
  1546. return os.path.join(self.data_path, 'tools_db.FlatDB')
  1547. def defaults_path(self):
  1548. return os.path.join(self.data_path, 'current_defaults.FlatConfig')
  1549. def factory_defaults_path(self):
  1550. return os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  1551. def recent_files_path(self):
  1552. return os.path.join(self.data_path, 'recent.json')
  1553. def recent_projects_path(self):
  1554. return os.path.join(self.data_path, 'recent_projects.json')
  1555. def preprocessors_path(self):
  1556. return os.path.join(self.data_path, 'preprocessors')
  1557. def on_app_restart(self):
  1558. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1559. # be left in the SySTray
  1560. try:
  1561. self.trayIcon.hide()
  1562. except Exception:
  1563. pass
  1564. fcTranslate.restart_program(app=self)
  1565. def clear_pool(self):
  1566. """
  1567. Clear the multiprocessing pool and calls garbage collector.
  1568. :return: None
  1569. """
  1570. self.pool.close()
  1571. self.pool = Pool()
  1572. self.pool_recreated.emit(self.pool)
  1573. gc.collect()
  1574. def install_tools(self):
  1575. """
  1576. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1577. Instantiation of the Tools classes.
  1578. The order that the tools are installed is important as they can depend on each other install position.
  1579. :return: None
  1580. """
  1581. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1582. self.shell = FCShell(app=self, version=self.version)
  1583. self.distance_tool = Distance(self)
  1584. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1585. before=self.ui.menueditorigin,
  1586. separator=False)
  1587. self.distance_min_tool = DistanceMin(self)
  1588. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1589. pos=self.ui.menuedit,
  1590. before=self.ui.menueditorigin,
  1591. separator=True)
  1592. self.dblsidedtool = DblSidedTool(self)
  1593. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1594. self.cal_exc_tool = ToolCalibration(self)
  1595. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1596. before=self.dblsidedtool.menuAction,
  1597. separator=False)
  1598. self.align_objects_tool = AlignObjects(self)
  1599. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1600. self.edrills_tool = ToolExtractDrills(self)
  1601. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1602. self.panelize_tool = Panelize(self)
  1603. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1604. self.film_tool = Film(self)
  1605. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1606. self.paste_tool = SolderPaste(self)
  1607. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1608. self.calculator_tool = ToolCalculator(self)
  1609. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1610. self.sub_tool = ToolSub(self)
  1611. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1612. pos=self.ui.menutool, separator=True)
  1613. self.rules_tool = RulesCheck(self)
  1614. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1615. pos=self.ui.menutool, separator=False)
  1616. self.optimal_tool = ToolOptimal(self)
  1617. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1618. pos=self.ui.menutool, separator=True)
  1619. self.move_tool = ToolMove(self)
  1620. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1621. before=self.ui.menueditorigin, separator=True)
  1622. self.cutout_tool = CutOut(self)
  1623. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1624. before=self.sub_tool.menuAction)
  1625. self.ncclear_tool = NonCopperClear(self)
  1626. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1627. before=self.sub_tool.menuAction, separator=True)
  1628. self.paint_tool = ToolPaint(self)
  1629. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1630. before=self.sub_tool.menuAction, separator=True)
  1631. self.isolation_tool = ToolIsolation(self)
  1632. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1633. before=self.sub_tool.menuAction, separator=True)
  1634. self.drilling_tool = ToolDrilling(self)
  1635. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1636. before=self.sub_tool.menuAction, separator=True)
  1637. self.copper_thieving_tool = ToolCopperThieving(self)
  1638. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1639. pos=self.ui.menutool)
  1640. self.fiducial_tool = ToolFiducials(self)
  1641. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1642. pos=self.ui.menutool)
  1643. self.qrcode_tool = QRCode(self)
  1644. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1645. pos=self.ui.menutool)
  1646. self.punch_tool = ToolPunchGerber(self)
  1647. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1648. self.invert_tool = ToolInvertGerber(self)
  1649. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1650. self.corners_tool = ToolCorners(self)
  1651. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1652. self.etch_tool = ToolEtchCompensation(self)
  1653. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1654. self.transform_tool = ToolTransform(self)
  1655. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1656. pos=self.ui.menuoptions, separator=True)
  1657. self.properties_tool = Properties(self)
  1658. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1659. pos=self.ui.menuoptions)
  1660. self.pdf_tool = ToolPDF(self)
  1661. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1662. pos=self.ui.menufileimport,
  1663. separator=True)
  1664. self.image_tool = ToolImage(self)
  1665. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1666. pos=self.ui.menufileimport,
  1667. separator=True)
  1668. self.pcb_wizard_tool = PcbWizard(self)
  1669. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1670. pos=self.ui.menufileimport)
  1671. self.log.debug("Tools are installed.")
  1672. def remove_tools(self):
  1673. """
  1674. Will remove all the actions in the Tool menu.
  1675. :return: None
  1676. """
  1677. for act in self.ui.menutool.actions():
  1678. self.ui.menutool.removeAction(act)
  1679. def init_tools(self):
  1680. """
  1681. Initialize the Tool tab in the notebook side of the central widget.
  1682. Remove the actions in the Tools menu.
  1683. Instantiate again the FlatCAM tools (plugins).
  1684. All this is required when changing the layout: standard, compact etc.
  1685. :return: None
  1686. """
  1687. self.log.debug("init_tools()")
  1688. # delete the data currently in the Tools Tab and the Tab itself
  1689. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1690. if widget is not None:
  1691. widget.deleteLater()
  1692. self.ui.notebook.removeTab(2)
  1693. # rebuild the Tools Tab
  1694. self.ui.tool_tab = QtWidgets.QWidget()
  1695. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1696. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1697. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1698. self.ui.tool_scroll_area = VerticalScrollArea()
  1699. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1700. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1701. # first remove all of them
  1702. self.remove_tools()
  1703. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1704. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1705. '&Command Line\tS')
  1706. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1707. # third install all of them
  1708. try:
  1709. self.install_tools()
  1710. except AttributeError:
  1711. pass
  1712. self.log.debug("Tools are initialized.")
  1713. # def parse_system_fonts(self):
  1714. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1715. # 'params': []})
  1716. def connect_tools_signals_to_toolbar(self, ui):
  1717. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1718. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1719. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1720. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1721. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1722. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1723. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1724. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1725. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1726. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1727. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1728. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1729. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1730. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1731. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1732. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1733. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1734. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1735. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1736. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1737. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1738. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1739. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1740. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1741. def connect_toolbar_signals(self, ui):
  1742. """
  1743. Reconnect the signals to the actions in the toolbar.
  1744. This has to be done each time after the FlatCAM tools are removed/installed.
  1745. :return: None
  1746. """
  1747. # Toolbar
  1748. # File Toolbar Signals
  1749. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1750. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1751. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1752. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1753. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1754. # View Toolbar Signals
  1755. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1756. ui.replot_btn.triggered.connect(self.plot_all)
  1757. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1758. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1759. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1760. # Edit Toolbar Signals
  1761. ui.editgeo_btn.triggered.connect(self.object2editor)
  1762. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1763. ui.copy_btn.triggered.connect(self.on_copy_command)
  1764. ui.delete_btn.triggered.connect(self.on_delete)
  1765. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1766. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1767. ui.origin_btn.triggered.connect(self.on_set_origin)
  1768. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1769. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1770. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1771. # Scripting Toolbar Signals
  1772. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1773. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1774. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1775. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1776. # Tools Toolbar Signals
  1777. try:
  1778. self.connect_tools_signals_to_toolbar(ui=ui)
  1779. except Exception as err:
  1780. self.log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1781. def object2editor(self):
  1782. """
  1783. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1784. :return: None
  1785. """
  1786. self.defaults.report_usage("object2editor()")
  1787. # disable the objects menu as it may interfere with the appEditors
  1788. self.ui.menuobjects.setDisabled(True)
  1789. edited_object = self.collection.get_active()
  1790. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1791. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1792. pass
  1793. else:
  1794. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1795. return
  1796. if isinstance(edited_object, GeometryObject):
  1797. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1798. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1799. # we set the notebook to hidden
  1800. # self.ui.splitter.setSizes([0, 1])
  1801. if edited_object.multigeo is True:
  1802. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1803. if len(sel_rows) > 1:
  1804. self.inform.emit('[WARNING_NOTCL] %s' %
  1805. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1806. "is not possible.\n"
  1807. "Edit only one geometry at a time."))
  1808. if not sel_rows:
  1809. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1810. return
  1811. # determine the tool dia of the selected tool
  1812. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1813. # now find the key in the edited_object.tools that has this tooldia
  1814. multi_tool = 1
  1815. for tool in edited_object.tools:
  1816. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1817. multi_tool = tool
  1818. break
  1819. self.log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1820. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1821. else:
  1822. self.log.debug("Editing SingleGeo Geometry with tool diameter.")
  1823. self.geo_editor.edit_fcgeometry(edited_object)
  1824. # set call source to the Editor we go into
  1825. self.call_source = 'geo_editor'
  1826. elif isinstance(edited_object, ExcellonObject):
  1827. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1828. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1829. if self.ui.splitter.sizes()[0] == 0:
  1830. self.ui.splitter.setSizes([1, 1])
  1831. self.exc_editor.edit_fcexcellon(edited_object)
  1832. # set call source to the Editor we go into
  1833. self.call_source = 'exc_editor'
  1834. elif isinstance(edited_object, GerberObject):
  1835. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1836. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1837. if self.ui.splitter.sizes()[0] == 0:
  1838. self.ui.splitter.setSizes([1, 1])
  1839. self.grb_editor.edit_fcgerber(edited_object)
  1840. # set call source to the Editor we go into
  1841. self.call_source = 'grb_editor'
  1842. # reset the following variables so the UI is built again after edit
  1843. edited_object.ui_build = False
  1844. elif isinstance(edited_object, CNCJobObject):
  1845. if self.ui.splitter.sizes()[0] == 0:
  1846. self.ui.splitter.setSizes([1, 1])
  1847. # set call source to the Editor we go into
  1848. self.call_source = 'gcode_editor'
  1849. self.gcode_editor.edit_fcgcode(edited_object)
  1850. # make sure that we can't select another object while in Editor Mode:
  1851. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1852. self.ui.project_frame.setDisabled(True)
  1853. # delete any selection shape that might be active as they are not relevant in Editor
  1854. self.delete_selection_shape()
  1855. # hide the Tools Toolbar
  1856. tools_tb = self.ui.toolbartools
  1857. if tools_tb.isVisible():
  1858. self.old_state_of_tools_toolbar = True
  1859. tools_tb.hide()
  1860. else:
  1861. self.old_state_of_tools_toolbar = False
  1862. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1863. self.ui.plot_tab_area.protectTab(0)
  1864. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1865. self.should_we_save = True
  1866. def editor2object(self, cleanup=None):
  1867. """
  1868. Transfers the Geometry or Excellon from it's editor to the current object.
  1869. :return: None
  1870. """
  1871. self.defaults.report_usage("editor2object()")
  1872. # re-enable the objects menu that was disabled on entry in Editor mode
  1873. self.ui.menuobjects.setDisabled(False)
  1874. # do not update a geometry or excellon object unless it comes out of an editor
  1875. if self.call_source != 'app':
  1876. edited_obj = self.collection.get_active()
  1877. if cleanup is None:
  1878. msgbox = QtWidgets.QMessageBox()
  1879. msgbox.setText(_("Do you want to save the edited object?"))
  1880. msgbox.setWindowTitle(_("Close Editor"))
  1881. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1882. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1883. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1884. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1885. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1886. msgbox.setDefaultButton(bt_yes)
  1887. msgbox.exec_()
  1888. response = msgbox.clickedButton()
  1889. if response == bt_yes:
  1890. # show the Tools Toolbar
  1891. tools_tb = self.ui.toolbartools
  1892. if self.old_state_of_tools_toolbar is True:
  1893. tools_tb.show()
  1894. # clean the Tools Tab
  1895. self.ui.tool_scroll_area.takeWidget()
  1896. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1897. self.ui.notebook.setTabText(2, _("Tool"))
  1898. if edited_obj.kind == 'geometry':
  1899. obj_type = "Geometry"
  1900. self.geo_editor.update_fcgeometry(edited_obj)
  1901. # self.geo_editor.update_options(edited_obj)
  1902. # restore GUI to the Selected TAB
  1903. # Remove anything else in the appGUI
  1904. self.ui.tool_scroll_area.takeWidget()
  1905. # update the geo object options so it is including the bounding box values
  1906. try:
  1907. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1908. edited_obj.options['xmin'] = xmin
  1909. edited_obj.options['ymin'] = ymin
  1910. edited_obj.options['xmax'] = xmax
  1911. edited_obj.options['ymax'] = ymax
  1912. except AttributeError as e:
  1913. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1914. self.log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1915. edited_obj.build_ui()
  1916. edited_obj.plot()
  1917. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1918. elif edited_obj.kind == 'gerber':
  1919. obj_type = "Gerber"
  1920. self.grb_editor.update_fcgerber()
  1921. # self.grb_editor.update_options(edited_obj)
  1922. # delete the old object (the source object) if it was an empty one
  1923. try:
  1924. if len(edited_obj.solid_geometry) == 0:
  1925. old_name = edited_obj.options['name']
  1926. self.collection.delete_by_name(old_name)
  1927. except TypeError:
  1928. # if the solid_geometry is a single Polygon the len() will not work
  1929. # in any case, falling here means that we have something in the solid_geometry, even if only
  1930. # a single Polygon, therefore we pass this
  1931. pass
  1932. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1933. # restore GUI to the Selected TAB
  1934. # Remove anything else in the GUI
  1935. self.ui.properties_scroll_area.takeWidget()
  1936. elif edited_obj.kind == 'excellon':
  1937. obj_type = "Excellon"
  1938. self.exc_editor.update_fcexcellon(edited_obj)
  1939. # self.exc_editor.update_options(edited_obj)
  1940. # restore GUI to the Selected TAB
  1941. # Remove anything else in the GUI
  1942. self.ui.tool_scroll_area.takeWidget()
  1943. # delete the old object (the source object) if it was an empty one
  1944. # find if we have drills:
  1945. has_drills = None
  1946. for tt in edited_obj.tools:
  1947. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1948. has_drills = True
  1949. break
  1950. # find if we have slots:
  1951. has_slots = None
  1952. for tt in edited_obj.tools:
  1953. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1954. has_slots = True
  1955. break
  1956. if has_drills is None and has_slots is None:
  1957. old_name = edited_obj.options['name']
  1958. self.collection.delete_by_name(name=old_name)
  1959. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1960. elif edited_obj.kind == 'cncjob':
  1961. obj_type = "CNCJob"
  1962. self.gcode_editor.update_fcgcode(edited_obj)
  1963. # self.exc_editor.update_options(edited_obj)
  1964. # restore GUI to the Selected TAB
  1965. # Remove anything else in the GUI
  1966. self.ui.tool_scroll_area.takeWidget()
  1967. edited_obj.build_ui()
  1968. # close the open tab
  1969. for idx in range(self.ui.plot_tab_area.count()):
  1970. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1971. self.ui.plot_tab_area.closeTab(idx)
  1972. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1973. else:
  1974. self.inform.emit('[WARNING_NOTCL] %s' %
  1975. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1976. return
  1977. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1978. elif response == bt_no:
  1979. # show the Tools Toolbar
  1980. tools_tb = self.ui.toolbartools
  1981. if self.old_state_of_tools_toolbar is True:
  1982. tools_tb.show()
  1983. # clean the Tools Tab
  1984. self.ui.tool_scroll_area.takeWidget()
  1985. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1986. self.ui.notebook.setTabText(2, _("Tool"))
  1987. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1988. if edited_obj.kind == 'geometry':
  1989. self.geo_editor.deactivate()
  1990. edited_obj.build_ui()
  1991. edited_obj.plot()
  1992. elif edited_obj.kind == 'gerber':
  1993. self.grb_editor.deactivate_grb_editor()
  1994. edited_obj.build_ui()
  1995. elif edited_obj.kind == 'excellon':
  1996. self.exc_editor.deactivate()
  1997. edited_obj.build_ui()
  1998. elif edited_obj.kind == 'cncjob':
  1999. self.gcode_editor.deactivate()
  2000. edited_obj.build_ui()
  2001. # close the open tab
  2002. for idx in range(self.ui.plot_tab_area.count()):
  2003. try:
  2004. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2005. self.ui.plot_tab_area.closeTab(idx)
  2006. except AttributeError:
  2007. continue
  2008. else:
  2009. self.inform.emit('[WARNING_NOTCL] %s' %
  2010. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2011. return
  2012. elif response == bt_cancel:
  2013. return
  2014. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2015. # edited_obj.build_ui()
  2016. # Switch notebook to Properties page
  2017. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2018. else:
  2019. # show the Tools Toolbar
  2020. tools_tb = self.ui.toolbartools
  2021. if self.old_state_of_tools_toolbar is True:
  2022. tools_tb.show()
  2023. if isinstance(edited_obj, GeometryObject):
  2024. self.geo_editor.deactivate()
  2025. elif isinstance(edited_obj, GerberObject):
  2026. self.grb_editor.deactivate_grb_editor()
  2027. elif isinstance(edited_obj, ExcellonObject):
  2028. self.exc_editor.deactivate()
  2029. else:
  2030. self.inform.emit('[WARNING_NOTCL] %s' %
  2031. _("Select a Gerber, Geometry or Excellon Object to update."))
  2032. return
  2033. # if notebook is hidden we show it
  2034. if self.ui.splitter.sizes()[0] == 0:
  2035. self.ui.splitter.setSizes([1, 1])
  2036. # restore the call_source to app
  2037. self.call_source = 'app'
  2038. # edited_obj.plot()
  2039. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2040. self.ui.plot_tab_area.protectTab(0)
  2041. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2042. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2043. self.ui.project_frame.setDisabled(False)
  2044. def get_last_folder(self):
  2045. """
  2046. Get the folder path from where the last file was opened.
  2047. :return: String, last opened folder path
  2048. """
  2049. return self.defaults["global_last_folder"]
  2050. def get_last_save_folder(self):
  2051. """
  2052. Get the folder path from where the last file was saved.
  2053. :return: String, last saved folder path
  2054. """
  2055. loc = self.defaults["global_last_save_folder"]
  2056. if loc is None:
  2057. loc = self.defaults["global_last_folder"]
  2058. if loc is None:
  2059. loc = os.path.dirname(__file__)
  2060. return loc
  2061. @QtCore.pyqtSlot(str)
  2062. @QtCore.pyqtSlot(str, bool)
  2063. def info(self, msg, shell_echo=True):
  2064. """
  2065. Informs the user. Normally on the status bar, optionally
  2066. also on the shell.
  2067. :param msg: Text to write.
  2068. :type msg: str
  2069. :param shell_echo: Control if to display the message msg in the Shell
  2070. :type shell_echo: bool
  2071. :return: None
  2072. """
  2073. # Type of message in brackets at the beginning of the message.
  2074. match = re.search(r"\[(.*)\](.*)", msg)
  2075. if match:
  2076. level = match.group(1)
  2077. msg_ = match.group(2)
  2078. self.ui.fcinfo.set_status(str(msg_), level=level)
  2079. if shell_echo is True:
  2080. if level.lower() == "error":
  2081. self.shell_message(msg, error=True, show=True)
  2082. elif level.lower() == "warning":
  2083. self.shell_message(msg, warning=True, show=True)
  2084. elif level.lower() == "error_notcl":
  2085. self.shell_message(msg, error=True, show=False)
  2086. elif level.lower() == "warning_notcl":
  2087. self.shell_message(msg, warning=True, show=False)
  2088. elif level.lower() == "success":
  2089. self.shell_message(msg, success=True, show=False)
  2090. elif level.lower() == "selected":
  2091. self.shell_message(msg, selected=True, show=False)
  2092. else:
  2093. self.shell_message(msg, show=False)
  2094. else:
  2095. self.ui.fcinfo.set_status(str(msg), level="info")
  2096. # make sure that if the message is to clear the infobar with a space
  2097. # is not printed over and over on the shell
  2098. if msg != '' and shell_echo is True:
  2099. self.shell_message(msg)
  2100. def info_shell(self, msg, new_line=True):
  2101. self.shell_message(msg=msg, new_line=new_line)
  2102. def save_to_file(self, content_to_save, txt_content):
  2103. """
  2104. Save something to a file.
  2105. :return: None
  2106. """
  2107. self.defaults.report_usage("save_to_file")
  2108. self.log.debug("save_to_file()")
  2109. self.date = str(datetime.today()).rpartition('.')[0]
  2110. self.date = ''.join(c for c in self.date if c not in ':-')
  2111. self.date = self.date.replace(' ', '_')
  2112. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2113. path_to_save = self.defaults["global_last_save_folder"] if \
  2114. self.defaults["global_last_save_folder"] is not None else self.data_path
  2115. try:
  2116. filename, _f = FCFileSaveDialog.get_saved_filename(
  2117. caption=_("Save to file"),
  2118. directory=path_to_save + '/file_' + self.date,
  2119. ext_filter=filter__
  2120. )
  2121. except TypeError:
  2122. filename, _f = FCFileSaveDialog.get_saved_filename(
  2123. caption=_("Save to file"),
  2124. ext_filter=filter__)
  2125. filename = str(filename)
  2126. if filename == "":
  2127. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2128. return
  2129. else:
  2130. try:
  2131. with open(filename, 'w') as f:
  2132. ___ = f.read()
  2133. except PermissionError:
  2134. self.inform.emit('[WARNING] %s' %
  2135. _("Permission denied, saving not possible.\n"
  2136. "Most likely another app is holding the file open and not accessible."))
  2137. return
  2138. except IOError:
  2139. self.log.debug('Creating a new file ...')
  2140. f = open(filename, 'w')
  2141. f.close()
  2142. except Exception:
  2143. e = sys.exc_info()[0]
  2144. App.log.error("Could not load the file.")
  2145. App.log.error(str(e))
  2146. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2147. return
  2148. # Save content
  2149. if filename.rpartition('.')[2].lower() == 'html':
  2150. file_content = content_to_save
  2151. else:
  2152. file_content = txt_content
  2153. try:
  2154. with open(filename, "w") as f:
  2155. f.write(file_content)
  2156. except Exception:
  2157. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2158. return
  2159. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2160. def register_recent(self, kind, filename):
  2161. """
  2162. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2163. dictionary.
  2164. :param kind: type of file that was opened
  2165. :param filename: the path and file name for the file that was opened
  2166. :return:
  2167. """
  2168. self.log.debug("register_recent()")
  2169. self.log.debug(" %s" % kind)
  2170. self.log.debug(" %s" % filename)
  2171. record = {'kind': str(kind), 'filename': str(filename)}
  2172. if record in self.recent:
  2173. return
  2174. if record in self.recent_projects:
  2175. return
  2176. if record['kind'] == 'project':
  2177. self.recent_projects.insert(0, record)
  2178. else:
  2179. self.recent.insert(0, record)
  2180. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2181. self.recent.pop()
  2182. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2183. self.recent_projects.pop()
  2184. try:
  2185. f = open(self.data_path + '/recent.json', 'w')
  2186. except IOError:
  2187. App.log.error("Failed to open recent items file for writing.")
  2188. self.inform.emit('[ERROR_NOTCL] %s' %
  2189. _('Failed to open recent files file for writing.'))
  2190. return
  2191. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2192. f.close()
  2193. try:
  2194. fp = open(self.data_path + '/recent_projects.json', 'w')
  2195. except IOError:
  2196. App.log.error("Failed to open recent items file for writing.")
  2197. self.inform.emit('[ERROR_NOTCL] %s' %
  2198. _('Failed to open recent projects file for writing.'))
  2199. return
  2200. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2201. fp.close()
  2202. # Re-build the recent items menu
  2203. self.setup_recent_items()
  2204. def on_about(self):
  2205. """
  2206. Displays the "about" dialog found in the Menu --> Help.
  2207. :return: None
  2208. """
  2209. self.defaults.report_usage("on_about")
  2210. version = self.version
  2211. version_date = self.version_date
  2212. beta = self.beta
  2213. class AboutDialog(QtWidgets.QDialog):
  2214. def __init__(self, app, parent=None):
  2215. QtWidgets.QDialog.__init__(self, parent)
  2216. self.app = app
  2217. # Icon and title
  2218. self.setWindowIcon(parent.app_icon)
  2219. self.setWindowTitle(_("About"))
  2220. self.resize(600, 200)
  2221. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2222. # self.setStyleSheet(
  2223. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2224. # "background-attachment: fixed"
  2225. # )
  2226. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2227. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2228. # palette = QtGui.QPalette()
  2229. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2230. # self.setPalette(palette)
  2231. logo = QtWidgets.QLabel()
  2232. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2233. title = QtWidgets.QLabel(
  2234. "<font size=8><B>FlatCAM</B></font><BR>"
  2235. "{title}<BR>"
  2236. "<BR>"
  2237. "<BR>"
  2238. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2239. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2240. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2241. "<B>{issue}</B></a><BR>".format(
  2242. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2243. devel=_("Development"),
  2244. down=_("DOWNLOAD"),
  2245. issue=_("Issue tracker"))
  2246. )
  2247. title.setOpenExternalLinks(True)
  2248. closebtn = QtWidgets.QPushButton(_("Close"))
  2249. tab_widget = QtWidgets.QTabWidget()
  2250. description_label = QtWidgets.QLabel(
  2251. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2252. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2253. version=version,
  2254. beta=('BETA' if beta else ''),
  2255. date=version_date,
  2256. arch=platform.architecture()[0])
  2257. )
  2258. description_label.setOpenExternalLinks(True)
  2259. lic_lbl_header = QtWidgets.QLabel(
  2260. '%s:<br>%s<br>' % (
  2261. _('Licensed under the MIT license'),
  2262. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2263. "http://www.opensource.org/licenses/mit-license.php</a>"
  2264. )
  2265. )
  2266. lic_lbl_header.setOpenExternalLinks(True)
  2267. lic_lbl_body = QtWidgets.QLabel(
  2268. _(
  2269. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2270. 'of this software and associated documentation files (the "Software"), to deal\n'
  2271. 'in the Software without restriction, including without limitation the rights\n'
  2272. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2273. 'copies of the Software, and to permit persons to whom the Software is\n'
  2274. 'furnished to do so, subject to the following conditions:\n\n'
  2275. 'The above copyright notice and this permission notice shall be included in\n'
  2276. 'all copies or substantial portions of the Software.\n\n'
  2277. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2278. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2279. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2280. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2281. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2282. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2283. 'THE SOFTWARE.'
  2284. )
  2285. )
  2286. attributions_label = QtWidgets.QLabel(
  2287. _(
  2288. 'Some of the icons used are from the following sources:<br>'
  2289. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2290. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2291. 'title="Flaticon">www.flaticon.com</a></div>'
  2292. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2293. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2294. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2295. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2296. 'title="Flaticon">www.flaticon.com</a></div>'
  2297. )
  2298. )
  2299. attributions_label.setOpenExternalLinks(True)
  2300. # layouts
  2301. layout1 = QtWidgets.QVBoxLayout()
  2302. layout1_1 = QtWidgets.QHBoxLayout()
  2303. layout1_2 = QtWidgets.QHBoxLayout()
  2304. layout2 = QtWidgets.QHBoxLayout()
  2305. layout3 = QtWidgets.QHBoxLayout()
  2306. self.setLayout(layout1)
  2307. layout1.addLayout(layout1_1)
  2308. layout1.addLayout(layout1_2)
  2309. layout1.addLayout(layout2)
  2310. layout1.addLayout(layout3)
  2311. layout1_1.addStretch()
  2312. layout1_1.addWidget(description_label)
  2313. layout1_2.addWidget(tab_widget)
  2314. self.splash_tab = QtWidgets.QWidget()
  2315. self.splash_tab.setObjectName("splash_about")
  2316. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2317. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2318. tab_widget.addTab(self.splash_tab, _("Splash"))
  2319. self.programmmers_tab = QtWidgets.QWidget()
  2320. self.programmmers_tab.setObjectName("programmers_about")
  2321. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2322. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2323. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2324. self.translators_tab = QtWidgets.QWidget()
  2325. self.translators_tab.setObjectName("translators_about")
  2326. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2327. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2328. tab_widget.addTab(self.translators_tab, _("Translators"))
  2329. self.license_tab = QtWidgets.QWidget()
  2330. self.license_tab.setObjectName("license_about")
  2331. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2332. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2333. tab_widget.addTab(self.license_tab, _("License"))
  2334. self.attributions_tab = QtWidgets.QWidget()
  2335. self.attributions_tab.setObjectName("attributions_about")
  2336. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2337. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2338. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2339. self.splash_tab_layout.addWidget(logo, stretch=0)
  2340. self.splash_tab_layout.addWidget(title, stretch=1)
  2341. pal = QtGui.QPalette()
  2342. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2343. self.prog_grid_lay = QtWidgets.QGridLayout()
  2344. self.prog_grid_lay.setHorizontalSpacing(20)
  2345. self.prog_grid_lay.setColumnStretch(0, 0)
  2346. self.prog_grid_lay.setColumnStretch(2, 1)
  2347. prog_widget = QtWidgets.QWidget()
  2348. prog_widget.setLayout(self.prog_grid_lay)
  2349. prog_scroll = QtWidgets.QScrollArea()
  2350. prog_scroll.setWidget(prog_widget)
  2351. prog_scroll.setWidgetResizable(True)
  2352. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2353. prog_scroll.setPalette(pal)
  2354. self.programmmers_tab_layout.addWidget(prog_scroll)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2402. self.translator_grid_lay = QtWidgets.QGridLayout()
  2403. self.translator_grid_lay.setColumnStretch(0, 0)
  2404. self.translator_grid_lay.setColumnStretch(1, 0)
  2405. self.translator_grid_lay.setColumnStretch(2, 1)
  2406. self.translator_grid_lay.setColumnStretch(3, 0)
  2407. # trans_widget = QtWidgets.QWidget()
  2408. # trans_widget.setLayout(self.translator_grid_lay)
  2409. # self.translators_tab_layout.addWidget(trans_widget)
  2410. # self.translators_tab_layout.addStretch()
  2411. trans_widget = QtWidgets.QWidget()
  2412. trans_widget.setLayout(self.translator_grid_lay)
  2413. trans_scroll = QtWidgets.QScrollArea()
  2414. trans_scroll.setWidget(trans_widget)
  2415. trans_scroll.setWidgetResizable(True)
  2416. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2417. trans_scroll.setPalette(pal)
  2418. self.translators_tab_layout.addWidget(trans_scroll)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2430. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2431. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2432. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2433. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2449. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2450. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2451. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2452. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2453. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2454. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2455. self.translator_grid_lay.setColumnStretch(0, 0)
  2456. self.translators_tab_layout.addStretch()
  2457. self.license_tab_layout.addWidget(lic_lbl_header)
  2458. self.license_tab_layout.addWidget(lic_lbl_body)
  2459. self.license_tab_layout.addStretch()
  2460. self.attributions_tab_layout.addWidget(attributions_label)
  2461. self.attributions_tab_layout.addStretch()
  2462. layout3.addStretch()
  2463. layout3.addWidget(closebtn)
  2464. closebtn.clicked.connect(self.accept)
  2465. AboutDialog(app=self, parent=self.ui).exec_()
  2466. def on_howto(self):
  2467. """
  2468. Displays the "about" dialog found in the Menu --> Help.
  2469. :return: None
  2470. """
  2471. class HowtoDialog(QtWidgets.QDialog):
  2472. def __init__(self, app, parent=None):
  2473. QtWidgets.QDialog.__init__(self, parent)
  2474. self.app = app
  2475. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2476. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2477. "<b>click</b></a>"
  2478. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2479. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2480. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2481. # Icon and title
  2482. self.setWindowIcon(parent.app_icon)
  2483. self.setWindowTitle('%s ...' % _("How To"))
  2484. self.resize(750, 375)
  2485. logo = QtWidgets.QLabel()
  2486. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2487. # content = QtWidgets.QLabel(
  2488. # "%s<br>"
  2489. # "%s<br><br>"
  2490. # "%s,<br>"
  2491. # "%s<br>"
  2492. # "<ul>"
  2493. # "<li> &nbsp;%s %s</li>"
  2494. # "<li> &nbsp;%s %s</li>"
  2495. # "</ul>"
  2496. # "%s %s.<br>"
  2497. # "%s"
  2498. # "<ul>"
  2499. # "<li> &nbsp;%s &#128077;</li>"
  2500. # "<li> &nbsp;%s &#128513;</li>"
  2501. # "</ul>" %
  2502. # (
  2503. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2504. # _("Yet it cannot evolve without <b>contributions</b>."),
  2505. # _("If you want to see this application grow and become better and better"),
  2506. # _("you can <b>contribute</b> to the development yourself by:"),
  2507. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2508. # new_features_link,
  2509. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2510. # bugs_link,
  2511. # _("If you like or use this program you can make a donation"),
  2512. # donation_link,
  2513. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2514. # _("it will be welcomed with joy"),
  2515. # _("it will give me a reason to continue")
  2516. # )
  2517. # )
  2518. # font-weight: bold;
  2519. content = QtWidgets.QLabel(
  2520. "%s<br>"
  2521. "%s<br><br>"
  2522. "%s,<br>"
  2523. "%s<br>"
  2524. "<ul>"
  2525. "<li> &nbsp;%s %s</li>"
  2526. "<li> &nbsp;%s %s</li>"
  2527. "</ul>"
  2528. "<br><br>"
  2529. "%s <br>"
  2530. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2531. (
  2532. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2533. _("Yet it cannot evolve without <b>contributions</b>."),
  2534. _("If you want to see this application grow and become better and better"),
  2535. _("you can <b>contribute</b> to the development yourself by:"),
  2536. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2537. new_features_link,
  2538. _("Bug Reports by providing the steps required to reproduce the bug"),
  2539. bugs_link,
  2540. _("If you like what you have seen so far ..."),
  2541. _("Donations are NOT required."), _("But they are welcomed"),
  2542. donation_link
  2543. )
  2544. )
  2545. content.setOpenExternalLinks(True)
  2546. # palette
  2547. pal = QtGui.QPalette()
  2548. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2549. # layouts
  2550. main_layout = QtWidgets.QVBoxLayout()
  2551. self.setLayout(main_layout)
  2552. tab_layout = QtWidgets.QHBoxLayout()
  2553. buttons_hlay = QtWidgets.QHBoxLayout()
  2554. main_layout.addLayout(tab_layout)
  2555. main_layout.addLayout(buttons_hlay)
  2556. tab_widget = QtWidgets.QTabWidget()
  2557. tab_layout.addWidget(tab_widget)
  2558. closebtn = QtWidgets.QPushButton(_("Close"))
  2559. buttons_hlay.addStretch()
  2560. buttons_hlay.addWidget(closebtn)
  2561. # CONTRIBUTE section
  2562. self.intro_tab = QtWidgets.QWidget()
  2563. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2564. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2565. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2566. self.grid_lay = QtWidgets.QGridLayout()
  2567. self.grid_lay.setHorizontalSpacing(20)
  2568. self.grid_lay.setColumnStretch(0, 0)
  2569. self.grid_lay.setColumnStretch(1, 1)
  2570. intro_wdg = QtWidgets.QWidget()
  2571. intro_wdg.setLayout(self.grid_lay)
  2572. intro_scroll_area = QtWidgets.QScrollArea()
  2573. intro_scroll_area.setWidget(intro_wdg)
  2574. intro_scroll_area.setWidgetResizable(True)
  2575. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2576. intro_scroll_area.setPalette(pal)
  2577. self.grid_lay.addWidget(logo, 0, 0)
  2578. self.grid_lay.addWidget(content, 0, 1)
  2579. self.intro_tab_layout.addWidget(intro_scroll_area)
  2580. # LINKS EXCHANGE section
  2581. self.links_tab = QtWidgets.QWidget()
  2582. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2583. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2584. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2585. self.links_lay = QtWidgets.QHBoxLayout()
  2586. links_wdg = QtWidgets.QWidget()
  2587. links_wdg.setLayout(self.links_lay)
  2588. links_scroll_area = QtWidgets.QScrollArea()
  2589. links_scroll_area.setWidget(links_wdg)
  2590. links_scroll_area.setWidgetResizable(True)
  2591. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2592. links_scroll_area.setPalette(pal)
  2593. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2594. self.links_tab_layout.addWidget(links_scroll_area)
  2595. # HOW TO section
  2596. self.howto_tab = QtWidgets.QWidget()
  2597. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2598. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2599. tab_widget.addTab(self.howto_tab, _("How To's"))
  2600. self.howto_lay = QtWidgets.QHBoxLayout()
  2601. howto_wdg = QtWidgets.QWidget()
  2602. howto_wdg.setLayout(self.howto_lay)
  2603. howto_scroll_area = QtWidgets.QScrollArea()
  2604. howto_scroll_area.setWidget(howto_wdg)
  2605. howto_scroll_area.setWidgetResizable(True)
  2606. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2607. howto_scroll_area.setPalette(pal)
  2608. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2609. self.howto_tab_layout.addWidget(howto_scroll_area)
  2610. # BUTTONS section
  2611. closebtn.clicked.connect(self.accept)
  2612. HowtoDialog(app=self, parent=self.ui).exec_()
  2613. def install_bookmarks(self, book_dict=None):
  2614. """
  2615. Install the bookmarks actions in the Help menu -> Bookmarks
  2616. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2617. :return: None
  2618. """
  2619. if book_dict is None:
  2620. self.defaults["global_bookmarks"].update(
  2621. {
  2622. '1': ['FlatCAM', "http://flatcam.org"],
  2623. '2': [_('Backup Site'), ""]
  2624. }
  2625. )
  2626. else:
  2627. self.defaults["global_bookmarks"].clear()
  2628. self.defaults["global_bookmarks"].update(book_dict)
  2629. # first try to disconnect if somehow they get connected from elsewhere
  2630. for act in self.ui.menuhelp_bookmarks.actions():
  2631. try:
  2632. act.triggered.disconnect()
  2633. except TypeError:
  2634. pass
  2635. # clear all actions except the last one who is the Bookmark manager
  2636. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2637. pass
  2638. else:
  2639. self.ui.menuhelp_bookmarks.removeAction(act)
  2640. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2641. if self.defaults["global_bookmarks"]:
  2642. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2643. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2644. # the JSON is first making the keys as strings (therefore I have to use strings too
  2645. # or do the conversion :(
  2646. # )
  2647. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2648. # the '10' entry jsut after '1' therefore ordering as strings
  2649. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2650. key=lambda x: int(x[0]))
  2651. for entry, bookmark in sorted_bookmarks:
  2652. title = bookmark[0]
  2653. weblink = bookmark[1]
  2654. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2655. act.setText(title)
  2656. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2657. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2658. if title == _('Backup Site') and weblink == "":
  2659. act.triggered.connect(self.on_backup_site)
  2660. else:
  2661. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2662. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2663. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2664. def on_bookmarks_manager(self):
  2665. """
  2666. Adds the bookmark manager in a Tab in Plot Area
  2667. :return:
  2668. """
  2669. for idx in range(self.ui.plot_tab_area.count()):
  2670. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2671. # there can be only one instance of Bookmark Manager at one time
  2672. return
  2673. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2674. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2675. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2676. # add the tab if it was closed
  2677. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2678. # delete the absolute and relative position and messages in the infobar
  2679. # self.ui.position_label.setText("")
  2680. # self.ui.rel_position_label.setText("")
  2681. # hide coordinates toolbars in the infobar while in DB
  2682. self.ui.coords_toolbar.hide()
  2683. self.ui.delta_coords_toolbar.hide()
  2684. # Switch plot_area to preferences page
  2685. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2686. def on_backup_site(self):
  2687. msgbox = QtWidgets.QMessageBox()
  2688. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2689. "1. FlatCAM.org website is down\n"
  2690. "2. Someone forked FlatCAM project and wants to point\n"
  2691. "to his own website\n\n"
  2692. "If you can't get any informations about the application\n"
  2693. "use the YouTube channel link from the Help menu."))
  2694. msgbox.setWindowTitle(_("Alternative website"))
  2695. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2696. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2697. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2698. msgbox.setDefaultButton(bt_yes)
  2699. msgbox.exec_()
  2700. # response = msgbox.clickedButton()
  2701. def final_save(self):
  2702. """
  2703. Callback for doing a preferences save to file whenever the application is about to quit.
  2704. If the project has changes, it will ask the user to save the project.
  2705. :return: None
  2706. """
  2707. if self.save_in_progress:
  2708. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2709. return
  2710. if self.should_we_save and self.collection.get_list():
  2711. msgbox = QtWidgets.QMessageBox()
  2712. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2713. "\n"
  2714. "Do you want to Save the project?"))
  2715. msgbox.setWindowTitle(_("Save changes"))
  2716. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2717. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2718. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2719. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2720. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2721. msgbox.setDefaultButton(bt_yes)
  2722. msgbox.exec_()
  2723. response = msgbox.clickedButton()
  2724. if response == bt_yes:
  2725. try:
  2726. self.trayIcon.hide()
  2727. except Exception:
  2728. pass
  2729. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2730. elif response == bt_no:
  2731. try:
  2732. self.trayIcon.hide()
  2733. except Exception:
  2734. pass
  2735. self.quit_application()
  2736. elif response == bt_cancel:
  2737. return
  2738. else:
  2739. try:
  2740. self.trayIcon.hide()
  2741. except Exception:
  2742. pass
  2743. self.quit_application()
  2744. def quit_application(self):
  2745. """
  2746. Called (as a pyslot or not) when the application is quit.
  2747. :return: None
  2748. """
  2749. # close editors before quiting the app, if they are open
  2750. if self.geo_editor.editor_active is True:
  2751. self.geo_editor.deactivate()
  2752. try:
  2753. self.geo_editor.disconnect()
  2754. except TypeError:
  2755. pass
  2756. self.log.debug("App.quit_application() --> Geo Editor deactivated.")
  2757. if self.exc_editor.editor_active is True:
  2758. self.exc_editor.deactivate()
  2759. try:
  2760. self.grb_editor.disconnect()
  2761. except TypeError:
  2762. pass
  2763. self.log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2764. if self.grb_editor.editor_active is True:
  2765. self.grb_editor.deactivate_grb_editor()
  2766. try:
  2767. self.exc_editor.disconnect()
  2768. except TypeError:
  2769. pass
  2770. self.log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2771. # disconnect the mouse events
  2772. if self.is_legacy:
  2773. self.plotcanvas.graph_event_disconnect(self.mm)
  2774. self.plotcanvas.graph_event_disconnect(self.mp)
  2775. self.plotcanvas.graph_event_disconnect(self.mr)
  2776. self.plotcanvas.graph_event_disconnect(self.mdc)
  2777. self.plotcanvas.graph_event_disconnect(self.kp)
  2778. else:
  2779. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2780. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2781. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2782. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2783. self.on_mouse_double_click_over_plot)
  2784. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2785. self.preferencesUiManager.save_defaults(silent=True)
  2786. self.log.debug("App.quit_application() --> App Defaults saved.")
  2787. if self.cmd_line_headless != 1:
  2788. # save app state to file
  2789. stgs = QSettings("Open Source", "FlatCAM")
  2790. stgs.setValue('saved_gui_state', self.ui.saveState())
  2791. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2792. stgs.setValue(
  2793. 'language',
  2794. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2795. )
  2796. stgs.setValue(
  2797. 'notebook_font_size',
  2798. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2799. )
  2800. stgs.setValue(
  2801. 'axis_font_size',
  2802. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2803. )
  2804. stgs.setValue(
  2805. 'textbox_font_size',
  2806. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2807. )
  2808. stgs.setValue(
  2809. 'hud_font_size',
  2810. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2811. )
  2812. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2813. stgs.setValue(
  2814. 'machinist',
  2815. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2816. )
  2817. # This will write the setting to the platform specific storage.
  2818. del stgs
  2819. self.log.debug("App.quit_application() --> App UI state saved.")
  2820. # try to quit the Socket opened by ArgsThread class
  2821. try:
  2822. # self.new_launch.thread_exit = True
  2823. # self.new_launch.listener.close()
  2824. self.new_launch.stop.emit()
  2825. except Exception as err:
  2826. self.log.debug("App.quit_application() --> %s" % str(err))
  2827. # try to quit the QThread that run ArgsThread class
  2828. try:
  2829. # del self.new_launch
  2830. self.listen_th.quit()
  2831. except Exception as e:
  2832. self.log.debug("App.quit_application() --> %s" % str(e))
  2833. # terminate workers
  2834. # self.workers.__del__()
  2835. self.clear_pool()
  2836. # quit app by signalling for self.kill_app() method
  2837. # self.close_app_signal.emit()
  2838. QtWidgets.qApp.quit()
  2839. sys.exit(0)
  2840. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2841. # we use the following command
  2842. # minor_v = sys.version_info.minor
  2843. # if minor_v < 8:
  2844. # # make sure that the app closes
  2845. # sys.exit(0)
  2846. # else:
  2847. # os._exit(0) # fix to work with Python 3.8
  2848. @staticmethod
  2849. def kill_app():
  2850. QtWidgets.qApp.quit()
  2851. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2852. # we use the following command
  2853. sys.exit(0)
  2854. def on_portable_checked(self, state):
  2855. """
  2856. Callback called when the checkbox in Preferences GUI is checked.
  2857. It will set the application as portable by creating the preferences and recent files in the
  2858. 'config' folder found in the FlatCAM installation folder.
  2859. :param state: boolean, the state of the checkbox when clicked/checked
  2860. :return:
  2861. """
  2862. line_no = 0
  2863. data = None
  2864. if sys.platform != 'win32':
  2865. # this won't work in Linux or MacOS
  2866. return
  2867. # test if the app was frozen and choose the path for the configuration file
  2868. if getattr(sys, "frozen", False) is True:
  2869. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2870. else:
  2871. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2872. config_file = current_data_path + '\\configuration.txt'
  2873. try:
  2874. with open(config_file, 'r') as f:
  2875. try:
  2876. data = f.readlines()
  2877. except Exception as e:
  2878. self.log.debug('App.__init__() -->%s' % str(e))
  2879. return
  2880. except FileNotFoundError:
  2881. pass
  2882. for line in data:
  2883. line = line.strip('\n')
  2884. param = str(line).rpartition('=')
  2885. if param[0] == 'portable':
  2886. break
  2887. line_no += 1
  2888. if state:
  2889. data[line_no] = 'portable=True\n'
  2890. # create the new defauults files
  2891. # create current_defaults.FlatConfig file if there is none
  2892. try:
  2893. f = open(current_data_path + '/current_defaults.FlatConfig')
  2894. f.close()
  2895. except IOError:
  2896. self.log.debug('Creating empty current_defaults.FlatConfig')
  2897. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2898. json.dump({}, f)
  2899. f.close()
  2900. # create factory_defaults.FlatConfig file if there is none
  2901. try:
  2902. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2903. f.close()
  2904. except IOError:
  2905. self.log.debug('Creating empty factory_defaults.FlatConfig')
  2906. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2907. json.dump({}, f)
  2908. f.close()
  2909. try:
  2910. f = open(current_data_path + '/recent.json')
  2911. f.close()
  2912. except IOError:
  2913. self.log.debug('Creating empty recent.json')
  2914. f = open(current_data_path + '/recent.json', 'w')
  2915. json.dump([], f)
  2916. f.close()
  2917. try:
  2918. fp = open(current_data_path + '/recent_projects.json')
  2919. fp.close()
  2920. except IOError:
  2921. self.log.debug('Creating empty recent_projects.json')
  2922. fp = open(current_data_path + '/recent_projects.json', 'w')
  2923. json.dump([], fp)
  2924. fp.close()
  2925. # save the current defaults to the new defaults file
  2926. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2927. else:
  2928. data[line_no] = 'portable=False\n'
  2929. with open(config_file, 'w') as f:
  2930. f.writelines(data)
  2931. def on_register_files(self, obj_type=None):
  2932. """
  2933. Called whenever there is a need to register file extensions with FlatCAM.
  2934. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2935. :param obj_type: the type of object to be register for.
  2936. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2937. :return: None
  2938. """
  2939. self.log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2940. new_reg_path = 'Software\\Classes\\'
  2941. # find if the current user is admin
  2942. try:
  2943. is_admin = os.getuid() == 0
  2944. except AttributeError:
  2945. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2946. if is_admin is True:
  2947. root_path = winreg.HKEY_LOCAL_MACHINE
  2948. else:
  2949. root_path = winreg.HKEY_CURRENT_USER
  2950. # create the keys
  2951. def set_reg(name, root_pth, new_reg_path_par, value):
  2952. try:
  2953. winreg.CreateKey(root_pth, new_reg_path_par)
  2954. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  2955. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2956. return True
  2957. except WindowsError:
  2958. return False
  2959. # delete key in registry
  2960. def delete_reg(root_pth, reg_path, key_to_del):
  2961. key_to_del_path = reg_path + key_to_del
  2962. try:
  2963. winreg.DeleteKey(root_pth, key_to_del_path)
  2964. return True
  2965. except WindowsError:
  2966. return False
  2967. if obj_type is None or obj_type == 'excellon':
  2968. exc_list = \
  2969. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2970. exc_list = [x for x in exc_list if x != '']
  2971. # register all keys in the Preferences window
  2972. for ext in exc_list:
  2973. new_k = new_reg_path + '.%s' % ext
  2974. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2975. # and unregister those that are no longer in the Preferences windows but are in the file
  2976. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2977. if ext not in exc_list:
  2978. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2979. # now write the updated extensions to the self.defaults
  2980. # new_ext = ''
  2981. # for ext in exc_list:
  2982. # new_ext = new_ext + ext + ', '
  2983. # self.defaults["fa_excellon"] = new_ext
  2984. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2985. if obj_type is None or obj_type == 'gcode':
  2986. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2987. gco_list = [x for x in gco_list if x != '']
  2988. # register all keys in the Preferences window
  2989. for ext in gco_list:
  2990. new_k = new_reg_path + '.%s' % ext
  2991. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2992. # and unregister those that are no longer in the Preferences windows but are in the file
  2993. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2994. if ext not in gco_list:
  2995. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2996. # now write the updated extensions to the self.defaults
  2997. # new_ext = ''
  2998. # for ext in gco_list:
  2999. # new_ext = new_ext + ext + ', '
  3000. # self.defaults["fa_gcode"] = new_ext
  3001. self.inform.emit('[success] %s' %
  3002. _("Selected GCode file extensions registered with FlatCAM."))
  3003. if obj_type is None or obj_type == 'gerber':
  3004. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3005. grb_list = [x for x in grb_list if x != '']
  3006. # register all keys in the Preferences window
  3007. for ext in grb_list:
  3008. new_k = new_reg_path + '.%s' % ext
  3009. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3010. # and unregister those that are no longer in the Preferences windows but are in the file
  3011. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3012. if ext not in grb_list:
  3013. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3014. # now write the updated extensions to the self.defaults
  3015. # new_ext = ''
  3016. # for ext in grb_list:
  3017. # new_ext = new_ext + ext + ', '
  3018. # self.defaults["fa_gerber"] = new_ext
  3019. self.inform.emit('[success] %s' %
  3020. _("Selected Gerber file extensions registered with FlatCAM."))
  3021. def add_extension(self, ext_type):
  3022. """
  3023. Add a file extension to the list for a specific object
  3024. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3025. :return:
  3026. """
  3027. if ext_type == 'excellon':
  3028. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3029. if new_ext == '':
  3030. return
  3031. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3032. if new_ext in old_val:
  3033. return
  3034. old_val.append(new_ext)
  3035. old_val.sort()
  3036. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3037. if ext_type == 'gcode':
  3038. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3039. if new_ext == '':
  3040. return
  3041. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3042. if new_ext in old_val:
  3043. return
  3044. old_val.append(new_ext)
  3045. old_val.sort()
  3046. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3047. if ext_type == 'gerber':
  3048. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3049. if new_ext == '':
  3050. return
  3051. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3052. if new_ext in old_val:
  3053. return
  3054. old_val.append(new_ext)
  3055. old_val.sort()
  3056. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3057. if ext_type == 'keyword':
  3058. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3059. if new_kw == '':
  3060. return
  3061. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3062. if new_kw in old_val:
  3063. return
  3064. old_val.append(new_kw)
  3065. old_val.sort()
  3066. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3067. # update the self.myKeywords so the model is updated
  3068. self.autocomplete_kw_list = \
  3069. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3070. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3071. self.shell.command_line().set_model_data(self.myKeywords)
  3072. def del_extension(self, ext_type):
  3073. """
  3074. Remove a file extension from the list for a specific object
  3075. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3076. :return:
  3077. """
  3078. if ext_type == 'excellon':
  3079. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3080. if new_ext == '':
  3081. return
  3082. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3083. if new_ext not in old_val:
  3084. return
  3085. old_val.remove(new_ext)
  3086. old_val.sort()
  3087. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3088. if ext_type == 'gcode':
  3089. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3090. if new_ext == '':
  3091. return
  3092. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3093. if new_ext not in old_val:
  3094. return
  3095. old_val.remove(new_ext)
  3096. old_val.sort()
  3097. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3098. if ext_type == 'gerber':
  3099. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3100. if new_ext == '':
  3101. return
  3102. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3103. if new_ext not in old_val:
  3104. return
  3105. old_val.remove(new_ext)
  3106. old_val.sort()
  3107. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3108. if ext_type == 'keyword':
  3109. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3110. if new_kw == '':
  3111. return
  3112. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3113. if new_kw not in old_val:
  3114. return
  3115. old_val.remove(new_kw)
  3116. old_val.sort()
  3117. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3118. # update the self.myKeywords so the model is updated
  3119. self.autocomplete_kw_list = \
  3120. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3121. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3122. self.shell.command_line().set_model_data(self.myKeywords)
  3123. def restore_extensions(self, ext_type):
  3124. """
  3125. Restore all file extensions associations with FlatCAM, for a specific object
  3126. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3127. :return:
  3128. """
  3129. if ext_type == 'excellon':
  3130. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3131. # for the ability to open Excellon files with .txt extension
  3132. new_exc_list = deepcopy(self.exc_list)
  3133. try:
  3134. new_exc_list.remove('txt')
  3135. except ValueError:
  3136. pass
  3137. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3138. if ext_type == 'gcode':
  3139. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3140. if ext_type == 'gerber':
  3141. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3142. if ext_type == 'keyword':
  3143. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3144. # update the self.myKeywords so the model is updated
  3145. self.autocomplete_kw_list = self.default_keywords
  3146. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3147. self.shell.commnad_line().set_model_data(self.myKeywords)
  3148. def delete_all_extensions(self, ext_type):
  3149. """
  3150. Delete all file extensions associations with FlatCAM, for a specific object
  3151. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3152. :return:
  3153. """
  3154. if ext_type == 'excellon':
  3155. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3156. if ext_type == 'gcode':
  3157. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3158. if ext_type == 'gerber':
  3159. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3160. if ext_type == 'keyword':
  3161. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3162. # update the self.myKeywords so the model is updated
  3163. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3164. self.shell.command_line().set_model_data(self.myKeywords)
  3165. def on_edit_join(self, name=None):
  3166. """
  3167. Callback for Edit->Join. Joins the selected geometry objects into
  3168. a new one.
  3169. :return: None
  3170. """
  3171. self.defaults.report_usage("on_edit_join()")
  3172. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3173. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3174. geo_type_set = set()
  3175. objs = self.collection.get_selected()
  3176. if len(objs) < 2:
  3177. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3178. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3179. return 'fail'
  3180. for obj in objs:
  3181. geo_type_set.add(obj.multigeo)
  3182. # if len(geo_type_list) == 1 means that all list elements are the same
  3183. if len(geo_type_set) != 1:
  3184. self.inform.emit('[ERROR] %s' %
  3185. _("Failed join. The Geometry objects are of different types.\n"
  3186. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3187. "convert from one to another and retry joining \n"
  3188. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3189. "the result may not be what was expected. \n"
  3190. "Check the generated GCODE."))
  3191. return
  3192. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3193. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3194. if True in geo_type_set:
  3195. def initialize(geo_obj, app):
  3196. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3197. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3198. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3199. for v in geo_obj.tools.values():
  3200. v['data']['name'] = obj_name_multi
  3201. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3202. else:
  3203. def initialize(geo_obj, app):
  3204. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3205. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3206. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3207. for v in geo_obj.tools.values():
  3208. v['data']['name'] = obj_name_single
  3209. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3210. self.should_we_save = True
  3211. def on_edit_join_exc(self):
  3212. """
  3213. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3214. a new Excellon.
  3215. :return: None
  3216. """
  3217. self.defaults.report_usage("on_edit_join_exc()")
  3218. objs = self.collection.get_selected()
  3219. for obj in objs:
  3220. if not isinstance(obj, ExcellonObject):
  3221. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3222. return
  3223. if len(objs) < 2:
  3224. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3225. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3226. return 'fail'
  3227. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3228. def initialize(exc_obj, app):
  3229. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3230. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3231. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3232. self.should_we_save = True
  3233. def on_edit_join_grb(self):
  3234. """
  3235. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3236. a new Gerber object.
  3237. :return: None
  3238. """
  3239. self.defaults.report_usage("on_edit_join_grb()")
  3240. objs = self.collection.get_selected()
  3241. for obj in objs:
  3242. if not isinstance(obj, GerberObject):
  3243. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3244. return
  3245. if len(objs) < 2:
  3246. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3247. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3248. return 'fail'
  3249. def initialize(grb_obj, app):
  3250. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3251. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3252. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3253. self.should_we_save = True
  3254. def on_convert_singlegeo_to_multigeo(self):
  3255. """
  3256. Called for converting a Geometry object from single-geo to multi-geo.
  3257. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3258. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3259. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3260. the solid-geometry of that tool.
  3261. :return: None
  3262. """
  3263. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3264. obj = self.collection.get_active()
  3265. if obj is None:
  3266. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3267. return
  3268. if not isinstance(obj, GeometryObject):
  3269. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3270. return
  3271. obj.multigeo = True
  3272. for tooluid, dict_value in obj.tools.items():
  3273. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3274. if not isinstance(obj.solid_geometry, list):
  3275. obj.solid_geometry = [obj.solid_geometry]
  3276. # obj.solid_geometry[:] = []
  3277. obj.plot()
  3278. self.should_we_save = True
  3279. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3280. def on_convert_multigeo_to_singlegeo(self):
  3281. """
  3282. Called for converting a Geometry object from multi-geo to single-geo.
  3283. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3284. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3285. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3286. the solid-geometry of that tool.
  3287. :return: None
  3288. """
  3289. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3290. obj = self.collection.get_active()
  3291. if obj is None:
  3292. self.inform.emit('[ERROR_NOTCL] %s' %
  3293. _("Failed. Select a Geometry Object and try again."))
  3294. return
  3295. if not isinstance(obj, GeometryObject):
  3296. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3297. (_("Expected a GeometryObject, got"), type(obj)))
  3298. return
  3299. obj.multigeo = False
  3300. total_solid_geometry = []
  3301. for tooluid, dict_value in obj.tools.items():
  3302. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3303. # clear the original geometry
  3304. dict_value['solid_geometry'][:] = []
  3305. obj.solid_geometry = deepcopy(total_solid_geometry)
  3306. obj.plot()
  3307. self.should_we_save = True
  3308. self.inform.emit('[success] %s' %
  3309. _("A Geometry object was converted to SingleGeo type."))
  3310. def on_defaults_dict_change(self, field):
  3311. """
  3312. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3313. Edit -> Preferences tab window.
  3314. :param field: the key of the self.defaults dictionary that was changed.
  3315. :return: None
  3316. """
  3317. self.preferencesUiManager.defaults_write_form_field(field=field)
  3318. if field == "units":
  3319. self.set_screen_units(self.defaults['units'])
  3320. def set_screen_units(self, units):
  3321. """
  3322. Set the FlatCAM units on the status bar.
  3323. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3324. :return: None
  3325. """
  3326. self.ui.units_label.setText("[" + units.lower() + "]")
  3327. def on_toggle_units_click(self):
  3328. try:
  3329. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3330. except (TypeError, AttributeError):
  3331. pass
  3332. if self.defaults["units"] == 'MM':
  3333. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3334. else:
  3335. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3336. self.on_toggle_units(no_pref=True)
  3337. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3338. lambda: self.on_toggle_units(no_pref=False))
  3339. def scale_defaults(self, sfactor, dimensions):
  3340. for dim in dimensions:
  3341. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3342. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3343. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3344. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3345. if not self.defaults[dim] or self.defaults[dim] == '':
  3346. continue
  3347. if isinstance(self.defaults[dim], str):
  3348. try:
  3349. tools_diameters = eval(self.defaults[dim])
  3350. except Exception as e:
  3351. self.log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3352. continue
  3353. elif isinstance(self.defaults[dim], (float, int)):
  3354. tools_diameters = [self.defaults[dim]]
  3355. else:
  3356. tools_diameters = list(self.defaults[dim])
  3357. if isinstance(tools_diameters, (tuple, list)):
  3358. pass
  3359. elif isinstance(tools_diameters, (int, float)):
  3360. tools_diameters = [self.defaults[dim]]
  3361. else:
  3362. continue
  3363. td_len = len(tools_diameters)
  3364. conv_list = []
  3365. for t in range(td_len):
  3366. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3367. self.defaults[dim] = conv_list
  3368. elif dim in ['global_gridx', 'global_gridy']:
  3369. # format the number of decimals to the one specified in self.decimals
  3370. try:
  3371. val = float(self.defaults[dim]) * sfactor
  3372. except Exception as e:
  3373. self.log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3374. continue
  3375. self.defaults[dim] = self.dec_format(val, self.decimals)
  3376. else:
  3377. # the number of decimals for the rest is kept unchanged
  3378. if self.defaults[dim]:
  3379. try:
  3380. val = float(self.defaults[dim]) * sfactor
  3381. except Exception as e:
  3382. self.log.debug(
  3383. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3384. )
  3385. continue
  3386. self.defaults[dim] = self.dec_format(val, self.decimals)
  3387. def on_toggle_units(self, no_pref=False):
  3388. """
  3389. Callback for the Units radio-button change in the Preferences tab.
  3390. Changes the application's default units adn for the project too.
  3391. If changing the project's units, the change propagates to all of
  3392. the objects in the project.
  3393. :return: None
  3394. """
  3395. self.defaults.report_usage("on_toggle_units")
  3396. if self.toggle_units_ignore:
  3397. return
  3398. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3399. # If option is the same, then ignore
  3400. if new_units == self.defaults["units"].upper():
  3401. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3402. return
  3403. # Keys in self.defaults for which to scale their values
  3404. dimensions = [
  3405. # Global
  3406. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3407. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3408. # Gerber Object
  3409. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3410. # Gerber Editor
  3411. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3412. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3413. # Excellon Object
  3414. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3415. # Excellon Editor
  3416. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3417. "excellon_editor_slot_length",
  3418. # Geometry Object
  3419. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3420. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3421. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3422. "geometry_extracut_length", "geometry_z_pdepth",
  3423. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3424. # CNCJob Object
  3425. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3426. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3427. # Isolation Tool
  3428. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3429. # Drilling Tool
  3430. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3431. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3432. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3433. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3434. # NCC Tool
  3435. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3436. "tools_ncc_newdia",
  3437. # Cutout Tool
  3438. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3439. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3440. # Paint Tool
  3441. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3442. # 2Sided Tool
  3443. "tools_2sided_drilldia",
  3444. # Film Tool
  3445. "tools_film_boundary", "tools_film_scale_stroke",
  3446. # Panel Tool
  3447. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3448. "tools_panelize_constrainy",
  3449. # Calculators Tool
  3450. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3451. # Transform Tool
  3452. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3453. "tools_transform_buffer_dis",
  3454. # SolderPaste Tool
  3455. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3456. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3457. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3458. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3459. # Corner Markers Tool
  3460. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3461. # Check Rules Tool
  3462. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3463. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3464. # QRCode Tool
  3465. "tools_qrcode_border_size",
  3466. # Copper Thieving Tool
  3467. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3468. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3469. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3470. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3471. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3472. "tools_copper_thieving_mask_clearance",
  3473. # Fiducials Tool
  3474. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3475. # Calibration Tool
  3476. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3477. # Drills Extraction Tool
  3478. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3479. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3480. # Punch Gerber Tool
  3481. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3482. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3483. # Invert Gerber Tool
  3484. "tools_invert_margin",
  3485. ]
  3486. # The scaling factor depending on choice of units.
  3487. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3488. # Changing project units. Warn user.
  3489. msgbox = QtWidgets.QMessageBox()
  3490. msgbox.setWindowTitle(_("Toggle Units"))
  3491. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3492. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3493. msgbox.setText(_("Changing the units of the project\n"
  3494. "will scale all objects.\n\n"
  3495. "Do you want to continue?"))
  3496. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3497. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3498. msgbox.setDefaultButton(bt_ok)
  3499. msgbox.exec_()
  3500. response = msgbox.clickedButton()
  3501. if response == bt_ok:
  3502. if no_pref is False:
  3503. self.preferencesUiManager.defaults_read_form()
  3504. self.scale_defaults(factor, dimensions)
  3505. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3506. self.defaults["units"] = new_units
  3507. # update the defaults from form, some may assume that the conversion is enough and it's not
  3508. self.on_options_app2project()
  3509. # update the objects
  3510. for obj in self.collection.get_list():
  3511. obj.convert_units(new_units)
  3512. # make that the properties stored in the object are also updated
  3513. self.app_obj.object_changed.emit(obj)
  3514. # rebuild the object UI
  3515. obj.build_ui()
  3516. # change this only if the workspace is active
  3517. if self.defaults['global_workspace'] is True:
  3518. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3519. # adjust the grid values on the main toolbar
  3520. val_x = float(self.defaults['global_gridx']) * factor
  3521. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3522. current = self.collection.get_active()
  3523. if current is not None:
  3524. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3525. if not isinstance(current, GeometryObject):
  3526. current.to_form()
  3527. # replot all objects
  3528. self.plot_all()
  3529. # set the status labels to reflect the current FlatCAM units
  3530. self.set_screen_units(new_units)
  3531. # signal to the app that we changed the object properties and it should save the project
  3532. self.should_we_save = True
  3533. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3534. else:
  3535. # Undo toggling
  3536. self.toggle_units_ignore = True
  3537. if self.defaults['units'].upper() == 'MM':
  3538. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3539. else:
  3540. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3541. self.toggle_units_ignore = False
  3542. # store the grid values so they are not changed in the next step
  3543. val_x = float(self.defaults['global_gridx'])
  3544. val_y = float(self.defaults['global_gridy'])
  3545. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3546. self.preferencesUiManager.defaults_read_form()
  3547. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3548. # in self.defaults from the GUI elements but
  3549. # I don't want it for the grid values, so I update them here
  3550. self.defaults['global_gridx'] = val_x
  3551. self.defaults['global_gridy'] = val_y
  3552. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3553. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3554. def on_deselect_all(self):
  3555. self.collection.set_all_inactive()
  3556. self.delete_selection_shape()
  3557. def on_workspace_modified(self):
  3558. # self.save_defaults(silent=True)
  3559. self.plotcanvas.delete_workspace()
  3560. self.preferencesUiManager.defaults_read_form()
  3561. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3562. def on_workspace(self):
  3563. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3564. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3565. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3566. else:
  3567. self.plotcanvas.delete_workspace()
  3568. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3569. self.preferencesUiManager.defaults_read_form()
  3570. # self.save_defaults(silent=True)
  3571. def on_workspace_toggle(self):
  3572. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3573. try:
  3574. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3575. except TypeError:
  3576. pass
  3577. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3578. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3579. self.on_workspace()
  3580. def on_cursor_type(self, val):
  3581. """
  3582. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3583. :return: None
  3584. """
  3585. self.app_cursor.enabled = False
  3586. if val == 'small':
  3587. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3588. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3589. self.app_cursor = self.plotcanvas.new_cursor()
  3590. else:
  3591. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3592. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3593. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3594. if self.ui.grid_snap_btn.isChecked():
  3595. self.app_cursor.enabled = True
  3596. else:
  3597. self.app_cursor.enabled = False
  3598. def on_tool_add_keypress(self):
  3599. # ## Current application units in Upper Case
  3600. self.units = self.defaults['units'].upper()
  3601. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3602. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3603. if notebook_widget_name == 'properties_tab':
  3604. if self.collection.get_active().kind == 'geometry':
  3605. # Tool add works for Geometry only if Advanced is True in Preferences
  3606. if self.defaults["global_app_level"] == 'a':
  3607. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3608. text='%s:' % _('Enter a Tool Diameter'),
  3609. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3610. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3611. val, ok = tool_add_popup.get_value()
  3612. if ok:
  3613. if float(val) == 0:
  3614. self.inform.emit('[WARNING_NOTCL] %s' %
  3615. _("Please enter a tool diameter with non-zero value, in Float format."))
  3616. return
  3617. self.collection.get_active().on_tool_add(dia=float(val))
  3618. else:
  3619. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3620. else:
  3621. msgbox = QtWidgets.QMessageBox()
  3622. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3623. "Go to Preferences -> General - Show Advanced Options."))
  3624. msgbox.setWindowTitle("Tool adding ...")
  3625. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3626. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3627. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3628. msgbox.setDefaultButton(bt_ok)
  3629. msgbox.exec_()
  3630. # work only if the notebook tab on focus is the Tools_Tab
  3631. if notebook_widget_name == 'tool_tab':
  3632. try:
  3633. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3634. except AttributeError:
  3635. return
  3636. # and only if the tool is NCC Tool
  3637. if tool_widget == self.ncclear_tool.toolName:
  3638. self.ncclear_tool.on_add_tool_by_key()
  3639. # and only if the tool is Paint Area Tool
  3640. elif tool_widget == self.paint_tool.toolName:
  3641. self.paint_tool.on_add_tool_by_key()
  3642. # and only if the tool is Solder Paste Dispensing Tool
  3643. elif tool_widget == self.paste_tool.toolName:
  3644. self.paste_tool.on_add_tool_by_key()
  3645. # and only if the tool is Isolation Tool
  3646. elif tool_widget == self.isolation_tool.toolName:
  3647. self.isolation_tool.on_add_tool_by_key()
  3648. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3649. # See description below.
  3650. def on_delete_keypress(self):
  3651. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3652. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3653. if notebook_widget_name == 'properties_tab':
  3654. if self.collection.get_active().kind == 'geometry':
  3655. self.collection.get_active().on_tool_delete()
  3656. # work only if the notebook tab on focus is the Tools_Tab
  3657. elif notebook_widget_name == 'tool_tab':
  3658. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3659. # and only if the tool is NCC Tool
  3660. if tool_widget == self.ncclear_tool.toolName:
  3661. self.ncclear_tool.on_tool_delete()
  3662. # and only if the tool is Paint Tool
  3663. elif tool_widget == self.paint_tool.toolName:
  3664. self.paint_tool.on_tool_delete()
  3665. # and only if the tool is Solder Paste Dispensing Tool
  3666. elif tool_widget == self.paste_tool.toolName:
  3667. self.paste_tool.on_tool_delete()
  3668. # and only if the tool is Isolation Tool
  3669. elif tool_widget == self.isolation_tool.toolName:
  3670. self.isolation_tool.on_tool_delete()
  3671. else:
  3672. self.on_delete()
  3673. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3674. # some screens you have to be careful where you hover with your mouse.
  3675. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3676. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3677. # Complicated, I know :)
  3678. def on_delete(self, force_deletion=False):
  3679. """
  3680. Delete the currently selected FlatCAMObjs.
  3681. :param force_deletion: used by Tcl command
  3682. :return: None
  3683. """
  3684. self.defaults.report_usage("on_delete()")
  3685. response = None
  3686. bt_ok = None
  3687. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3688. # a geometry object before we update it.
  3689. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3690. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3691. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3692. msgbox = QtWidgets.QMessageBox()
  3693. msgbox.setWindowTitle(_("Delete objects"))
  3694. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3695. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3696. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3697. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3698. "the selected objects?"))
  3699. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3700. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3701. msgbox.setDefaultButton(bt_ok)
  3702. msgbox.exec_()
  3703. response = msgbox.clickedButton()
  3704. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3705. response = bt_ok
  3706. if response == bt_ok:
  3707. if self.collection.get_active():
  3708. self.log.debug("App.on_delete()")
  3709. for obj_active in self.collection.get_selected():
  3710. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3711. if obj_active.kind == 'gerber':
  3712. obj_active.mark_shapes_storage.clear()
  3713. obj_active.mark_shapes.clear(update=True)
  3714. obj_active.mark_shapes.enabled = False
  3715. elif obj_active.kind == 'cncjob':
  3716. try:
  3717. obj_active.text_col.enabled = False
  3718. del obj_active.text_col
  3719. obj_active.annotation.clear(update=True)
  3720. del obj_active.annotation
  3721. obj_active.probing_shapes.clear(update=True)
  3722. except AttributeError as e:
  3723. self.log.debug(
  3724. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3725. )
  3726. while self.collection.get_selected():
  3727. self.delete_first_selected()
  3728. # make sure that the selection shape is deleted, too
  3729. self.delete_selection_shape()
  3730. # if there are no longer objects delete also the exclusion areas shapes
  3731. if not self.collection.get_list():
  3732. self.exc_areas.clear_shapes()
  3733. self.inform.emit('%s...' % _("Object(s) deleted"))
  3734. else:
  3735. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3736. else:
  3737. self.inform.emit(_("Save the work in Editor and try again ..."))
  3738. def delete_first_selected(self):
  3739. # Keep this for later
  3740. try:
  3741. sel_obj = self.collection.get_active()
  3742. name = sel_obj.options["name"]
  3743. isPlotted = sel_obj.options["plot"]
  3744. except AttributeError:
  3745. self.log.debug("Nothing selected for deletion")
  3746. return
  3747. if self.is_legacy is True:
  3748. # Remove plot only if the object was plotted otherwise delaxes will fail
  3749. if isPlotted:
  3750. try:
  3751. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3752. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3753. except Exception as e:
  3754. self.log.debug("App.delete_first_selected() --> %s" % str(e))
  3755. self.plotcanvas.auto_adjust_axes()
  3756. # Remove from dictionary
  3757. self.collection.delete_active()
  3758. # Clear form
  3759. self.setup_default_properties_tab()
  3760. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3761. def on_set_origin(self):
  3762. """
  3763. Set the origin to the left mouse click position
  3764. :return: None
  3765. """
  3766. # display the message for the user
  3767. # and ask him to click on the desired position
  3768. self.defaults.report_usage("on_set_origin()")
  3769. def origin_replot():
  3770. def worker_task():
  3771. with self.proc_container.new('%s...' % _("Plotting")):
  3772. for obj in self.collection.get_list():
  3773. obj.plot()
  3774. self.plotcanvas.fit_view()
  3775. if self.is_legacy:
  3776. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3777. else:
  3778. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3779. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3780. self.inform.emit(_('Click to set the origin ...'))
  3781. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3782. # first disconnect it as it may have been used by something else
  3783. try:
  3784. self.replot_signal.disconnect()
  3785. except TypeError:
  3786. pass
  3787. self.replot_signal[list].connect(origin_replot)
  3788. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3789. """
  3790. :param event:
  3791. :param location:
  3792. :param noplot:
  3793. :param use_thread:
  3794. :return:
  3795. """
  3796. noplot_sig = noplot
  3797. def worker_task():
  3798. with self.proc_container.new(_("Setting Origin...")):
  3799. obj_list = self.collection.get_list()
  3800. for obj in obj_list:
  3801. obj.offset((x, y))
  3802. self.app_obj.object_changed.emit(obj)
  3803. # Update the object bounding box options
  3804. a, b, c, d = obj.bounds()
  3805. obj.options['xmin'] = a
  3806. obj.options['ymin'] = b
  3807. obj.options['xmax'] = c
  3808. obj.options['ymax'] = d
  3809. self.inform.emit('[success] %s...' % _('Origin set'))
  3810. for obj in obj_list:
  3811. out_name = obj.options["name"]
  3812. if obj.kind == 'gerber':
  3813. obj.source_file = self.f_handlers.export_gerber(
  3814. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3815. elif obj.kind == 'excellon':
  3816. obj.source_file = self.f_handlers.export_excellon(
  3817. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3818. if noplot_sig is False:
  3819. self.replot_signal.emit([])
  3820. if location is not None:
  3821. if len(location) != 2:
  3822. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3823. return 'fail'
  3824. x, y = location
  3825. if use_thread is True:
  3826. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3827. else:
  3828. worker_task()
  3829. self.should_we_save = True
  3830. return
  3831. if event is not None and event.button == 1:
  3832. if self.is_legacy is False:
  3833. event_pos = event.pos
  3834. else:
  3835. event_pos = (event.xdata, event.ydata)
  3836. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3837. if self.grid_status():
  3838. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3839. else:
  3840. pos = pos_canvas
  3841. x = 0 - pos[0]
  3842. y = 0 - pos[1]
  3843. if use_thread is True:
  3844. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3845. else:
  3846. worker_task()
  3847. self.should_we_save = True
  3848. def on_move2origin(self, use_thread=True):
  3849. """
  3850. Move selected objects to origin.
  3851. :param use_thread: Control if to use threaded operation. Boolean.
  3852. :return:
  3853. """
  3854. def worker_task():
  3855. with self.proc_container.new(_("Moving to Origin...")):
  3856. obj_list = self.collection.get_selected()
  3857. if not obj_list:
  3858. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3859. return
  3860. xminlist = []
  3861. yminlist = []
  3862. # first get a bounding box to fit all
  3863. for obj in obj_list:
  3864. xmin, ymin, xmax, ymax = obj.bounds()
  3865. xminlist.append(xmin)
  3866. yminlist.append(ymin)
  3867. # get the minimum x,y for all objects selected
  3868. x = min(xminlist)
  3869. y = min(yminlist)
  3870. for obj in obj_list:
  3871. obj.offset((-x, -y))
  3872. self.app_obj.object_changed.emit(obj)
  3873. # Update the object bounding box options
  3874. a, b, c, d = obj.bounds()
  3875. obj.options['xmin'] = a
  3876. obj.options['ymin'] = b
  3877. obj.options['xmax'] = c
  3878. obj.options['ymax'] = d
  3879. for obj in obj_list:
  3880. obj.plot()
  3881. for obj in obj_list:
  3882. out_name = obj.options["name"]
  3883. if obj.kind == 'gerber':
  3884. obj.source_file = self.f_handlers.export_gerber(
  3885. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3886. elif obj.kind == 'excellon':
  3887. obj.source_file = self.f_handlers.export_excellon(
  3888. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3889. self.inform.emit('[success] %s...' % _('Origin set'))
  3890. if use_thread is True:
  3891. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3892. else:
  3893. worker_task()
  3894. self.should_we_save = True
  3895. def on_jump_to(self, custom_location=None, fit_center=True):
  3896. """
  3897. Jump to a location by setting the mouse cursor location.
  3898. :param custom_location: Jump to a specified point. (x, y) tuple.
  3899. :param fit_center: If to fit view. Boolean.
  3900. :return:
  3901. """
  3902. self.defaults.report_usage("on_jump_to()")
  3903. if not custom_location:
  3904. dia_box_location = None
  3905. try:
  3906. dia_box_location = eval(self.clipboard.text())
  3907. except Exception:
  3908. pass
  3909. if type(dia_box_location) == tuple:
  3910. dia_box_location = str(dia_box_location)
  3911. else:
  3912. dia_box_location = None
  3913. # dia_box = Dialog_box(title=_("Jump to ..."),
  3914. # label=_("Enter the coordinates in format X,Y:"),
  3915. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3916. # initial_text=dia_box_location)
  3917. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3918. label=_("Enter the coordinates in format X,Y:"),
  3919. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3920. initial_text=dia_box_location,
  3921. reference=self.defaults['global_jump_ref'])
  3922. if dia_box.ok is True:
  3923. try:
  3924. location = eval(dia_box.location)
  3925. if not isinstance(location, tuple):
  3926. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3927. return
  3928. if dia_box.reference == 'rel':
  3929. rel_x = self.mouse[0] + location[0]
  3930. rel_y = self.mouse[1] + location[1]
  3931. location = (rel_x, rel_y)
  3932. self.defaults['global_jump_ref'] = dia_box.reference
  3933. except Exception:
  3934. return
  3935. else:
  3936. return
  3937. else:
  3938. location = custom_location
  3939. self.jump_signal.emit(location)
  3940. if fit_center:
  3941. self.plotcanvas.fit_center(loc=location)
  3942. cursor = QtGui.QCursor()
  3943. if self.is_legacy is False:
  3944. # I don't know where those differences come from but they are constant for the current
  3945. # execution of the application and they are multiples of a value around 0.0263mm.
  3946. # In a random way sometimes they are more sometimes they are less
  3947. # if units == 'MM':
  3948. # cal_factor = 0.0263
  3949. # else:
  3950. # cal_factor = 0.0263 / 25.4
  3951. cal_location = (location[0], location[1])
  3952. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3953. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3954. j_pos = (
  3955. int(canvas_origin.x() + round(jump_loc[0])),
  3956. int(canvas_origin.y() + round(jump_loc[1]))
  3957. )
  3958. cursor.setPos(j_pos[0], j_pos[1])
  3959. else:
  3960. # find the canvas origin which is in the top left corner
  3961. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3962. # determine the coordinates for the lowest left point of the canvas
  3963. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3964. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3965. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3966. # canvas) and the point (width, height) is in the top-right location
  3967. loc = self.plotcanvas.axes.transData.transform_point(location)
  3968. j_pos = (
  3969. int(x0 + loc[0]),
  3970. int(y0 - loc[1])
  3971. )
  3972. cursor.setPos(j_pos[0], j_pos[1])
  3973. self.plotcanvas.mouse = [location[0], location[1]]
  3974. if self.defaults["global_cursor_color_enabled"] is True:
  3975. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3976. else:
  3977. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3978. if self.grid_status():
  3979. # Update cursor
  3980. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3981. symbol='++', edge_color=self.cursor_color_3D,
  3982. edge_width=self.defaults["global_cursor_width"],
  3983. size=self.defaults["global_cursor_size"])
  3984. # Set the relative position label
  3985. dx = location[0] - float(self.rel_point1[0])
  3986. dy = location[1] - float(self.rel_point1[1])
  3987. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3988. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3989. # Set the position label
  3990. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3991. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3992. units = self.defaults["units"].lower()
  3993. self.plotcanvas.text_hud.text = \
  3994. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3995. dx, units, dy, units, location[0], units, location[1], units)
  3996. self.inform.emit('[success] %s' % _("Done."))
  3997. return location
  3998. def on_locate(self, obj, fit_center=True):
  3999. """
  4000. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4001. :param obj: The object on which to locate certain points
  4002. :param fit_center: If to fit view. Boolean.
  4003. :return: A point location. (x, y) tuple.
  4004. """
  4005. self.defaults.report_usage("on_locate()")
  4006. if obj is None:
  4007. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4008. return 'fail'
  4009. class DialogBoxChoice(QtWidgets.QDialog):
  4010. def __init__(self, title=None, icon=None, choice='bl'):
  4011. """
  4012. :param title: string with the window title
  4013. """
  4014. super(DialogBoxChoice, self).__init__()
  4015. self.ok = False
  4016. self.setWindowIcon(icon)
  4017. self.setWindowTitle(str(title))
  4018. self.form = QtWidgets.QFormLayout(self)
  4019. self.ref_radio = RadioSet([
  4020. {"label": _("Bottom-Left"), "value": "bl"},
  4021. {"label": _("Top-Left"), "value": "tl"},
  4022. {"label": _("Bottom-Right"), "value": "br"},
  4023. {"label": _("Top-Right"), "value": "tr"},
  4024. {"label": _("Center"), "value": "c"}
  4025. ], orientation='vertical', stretch=False)
  4026. self.ref_radio.set_value(choice)
  4027. self.form.addRow(self.ref_radio)
  4028. self.button_box = QtWidgets.QDialogButtonBox(
  4029. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4030. Qt.Horizontal, parent=self)
  4031. self.form.addRow(self.button_box)
  4032. self.button_box.accepted.connect(self.accept)
  4033. self.button_box.rejected.connect(self.reject)
  4034. if self.exec_() == QtWidgets.QDialog.Accepted:
  4035. self.ok = True
  4036. self.location_point = self.ref_radio.get_value()
  4037. else:
  4038. self.ok = False
  4039. self.location_point = None
  4040. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4041. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4042. choice=self.defaults['global_locate_pt'])
  4043. if dia_box.ok is True:
  4044. try:
  4045. location_point = dia_box.location_point
  4046. self.defaults['global_locate_pt'] = dia_box.location_point
  4047. except Exception:
  4048. return
  4049. else:
  4050. return
  4051. loc_b = obj.bounds()
  4052. if location_point == 'bl':
  4053. location = (loc_b[0], loc_b[1])
  4054. elif location_point == 'tl':
  4055. location = (loc_b[0], loc_b[3])
  4056. elif location_point == 'br':
  4057. location = (loc_b[2], loc_b[1])
  4058. elif location_point == 'tr':
  4059. location = (loc_b[2], loc_b[3])
  4060. else:
  4061. # center
  4062. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4063. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4064. location = (cx, cy)
  4065. self.locate_signal.emit(location, location_point)
  4066. if fit_center:
  4067. self.plotcanvas.fit_center(loc=location)
  4068. cursor = QtGui.QCursor()
  4069. if self.is_legacy is False:
  4070. # I don't know where those differences come from but they are constant for the current
  4071. # execution of the application and they are multiples of a value around 0.0263mm.
  4072. # In a random way sometimes they are more sometimes they are less
  4073. # if units == 'MM':
  4074. # cal_factor = 0.0263
  4075. # else:
  4076. # cal_factor = 0.0263 / 25.4
  4077. cal_location = (location[0], location[1])
  4078. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4079. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4080. j_pos = (
  4081. int(canvas_origin.x() + round(jump_loc[0])),
  4082. int(canvas_origin.y() + round(jump_loc[1]))
  4083. )
  4084. cursor.setPos(j_pos[0], j_pos[1])
  4085. else:
  4086. # find the canvas origin which is in the top left corner
  4087. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4088. # determine the coordinates for the lowest left point of the canvas
  4089. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4090. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4091. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4092. # canvas) and the point (width, height) is in the top-right location
  4093. loc = self.plotcanvas.axes.transData.transform_point(location)
  4094. j_pos = (
  4095. int(x0 + loc[0]),
  4096. int(y0 - loc[1])
  4097. )
  4098. cursor.setPos(j_pos[0], j_pos[1])
  4099. self.plotcanvas.mouse = [location[0], location[1]]
  4100. if self.defaults["global_cursor_color_enabled"] is True:
  4101. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4102. else:
  4103. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4104. if self.grid_status():
  4105. # Update cursor
  4106. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4107. symbol='++', edge_color=self.cursor_color_3D,
  4108. edge_width=self.defaults["global_cursor_width"],
  4109. size=self.defaults["global_cursor_size"])
  4110. # Set the relative position label
  4111. self.dx = location[0] - float(self.rel_point1[0])
  4112. self.dy = location[1] - float(self.rel_point1[1])
  4113. # Set the position label
  4114. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4115. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4116. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4117. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4118. units = self.defaults["units"].lower()
  4119. self.plotcanvas.text_hud.text = \
  4120. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4121. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4122. self.inform.emit('[success] %s' % _("Done."))
  4123. return location
  4124. def on_copy_command(self):
  4125. """
  4126. Will copy a selection of objects, creating new objects.
  4127. :return:
  4128. """
  4129. self.defaults.report_usage("on_copy_command()")
  4130. def initialize(obj_init, app_obj):
  4131. """
  4132. :param obj_init: the new object
  4133. :type obj_init: class
  4134. :param app_obj: An instance of the App class
  4135. :type app_obj: App
  4136. :return: None
  4137. :rtype:
  4138. """
  4139. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4140. try:
  4141. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4142. except AttributeError:
  4143. pass
  4144. try:
  4145. obj_init.apertures = deepcopy(obj.apertures)
  4146. except AttributeError:
  4147. pass
  4148. try:
  4149. if obj.tools:
  4150. obj_init.tools = deepcopy(obj.tools)
  4151. except Exception as err:
  4152. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4153. try:
  4154. obj_init.source_file = deepcopy(obj.source_file)
  4155. except (AttributeError, TypeError):
  4156. pass
  4157. def initialize_excellon(obj_init, app_obj):
  4158. obj_init.source_file = deepcopy(obj.source_file)
  4159. obj_init.tools = deepcopy(obj.tools)
  4160. # drills are offset, so they need to be deep copied
  4161. obj_init.drills = deepcopy(obj.drills)
  4162. # slots are offset, so they need to be deep copied
  4163. obj_init.slots = deepcopy(obj.slots)
  4164. obj_init.create_geometry()
  4165. if not obj_init.tools:
  4166. app_obj.debug("on_copy_command() --> no excellon tools")
  4167. return 'fail'
  4168. def initialize_script(obj_init, app_obj):
  4169. obj_init.source_file = deepcopy(obj.source_file)
  4170. def initialize_document(obj_init, app_obj):
  4171. obj_init.source_file = deepcopy(obj.source_file)
  4172. for obj in self.collection.get_selected():
  4173. obj_name = obj.options["name"]
  4174. try:
  4175. if isinstance(obj, ExcellonObject):
  4176. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4177. elif isinstance(obj, GerberObject):
  4178. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4179. elif isinstance(obj, GeometryObject):
  4180. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4181. elif isinstance(obj, ScriptObject):
  4182. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4183. elif isinstance(obj, DocumentObject):
  4184. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4185. except Exception as e:
  4186. return "Operation failed: %s" % str(e)
  4187. def on_copy_object2(self, custom_name):
  4188. def initialize_geometry(obj_init, app_obj):
  4189. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4190. try:
  4191. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4192. except AttributeError:
  4193. pass
  4194. try:
  4195. obj_init.apertures = deepcopy(obj.apertures)
  4196. except AttributeError:
  4197. pass
  4198. try:
  4199. if obj.tools:
  4200. obj_init.tools = deepcopy(obj.tools)
  4201. except Exception as ee:
  4202. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4203. def initialize_gerber(obj_init, app_obj):
  4204. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4205. obj_init.apertures = deepcopy(obj.apertures)
  4206. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4207. if not obj_init.apertures:
  4208. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4209. return 'fail'
  4210. def initialize_excellon(obj_init, app_obj):
  4211. obj_init.tools = deepcopy(obj.tools)
  4212. # drills are offset, so they need to be deep copied
  4213. obj_init.drills = deepcopy(obj.drills)
  4214. # slots are offset, so they need to be deep copied
  4215. obj_init.slots = deepcopy(obj.slots)
  4216. obj_init.create_geometry()
  4217. if not obj_init.tools:
  4218. app_obj.debug("on_copy_object2() --> no excellon tools")
  4219. return 'fail'
  4220. for obj in self.collection.get_selected():
  4221. obj_name = obj.options["name"]
  4222. try:
  4223. if isinstance(obj, ExcellonObject):
  4224. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4225. elif isinstance(obj, GerberObject):
  4226. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4227. elif isinstance(obj, GeometryObject):
  4228. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4229. except Exception as er:
  4230. return "Operation failed: %s" % str(er)
  4231. def on_rename_object(self, text):
  4232. """
  4233. Will rename an object.
  4234. :param text: New name for the object.
  4235. :return:
  4236. """
  4237. self.defaults.report_usage("on_rename_object()")
  4238. named_obj = self.collection.get_active()
  4239. for obj in named_obj:
  4240. if obj is list:
  4241. self.on_rename_object(text)
  4242. else:
  4243. try:
  4244. obj.options['name'] = text
  4245. except Exception as e:
  4246. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4247. def convert_any2geo(self):
  4248. """
  4249. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4250. :return:
  4251. """
  4252. self.defaults.report_usage("convert_any2geo()")
  4253. def initialize(obj_init, app):
  4254. obj_init.solid_geometry = obj.solid_geometry
  4255. try:
  4256. obj_init.follow_geometry = obj.follow_geometry
  4257. except AttributeError:
  4258. pass
  4259. try:
  4260. obj_init.apertures = obj.apertures
  4261. except AttributeError:
  4262. pass
  4263. try:
  4264. if obj.tools:
  4265. obj_init.tools = obj.tools
  4266. except AttributeError:
  4267. pass
  4268. def initialize_excellon(obj_init, app_obj):
  4269. # objs = self.collection.get_selected()
  4270. # GeometryObject.merge(objs, obj)
  4271. solid_geo = []
  4272. for tool in obj.tools:
  4273. for geo in obj.tools[tool]['solid_geometry']:
  4274. solid_geo.append(geo)
  4275. obj_init.solid_geometry = deepcopy(solid_geo)
  4276. if not obj_init.solid_geometry:
  4277. app_obj.log("convert_any2geo() failed")
  4278. return 'fail'
  4279. if not self.collection.get_selected():
  4280. log.warning("App.convert_any2geo --> No object selected")
  4281. self.inform.emit('[WARNING_NOTCL] %s' %
  4282. _("No object is selected. Select an object and try again."))
  4283. return
  4284. for obj in self.collection.get_selected():
  4285. obj_name = obj.options["name"]
  4286. try:
  4287. if obj.kind == 'excellon':
  4288. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4289. else:
  4290. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4291. except Exception as e:
  4292. return "Operation failed: %s" % str(e)
  4293. def convert_any2gerber(self):
  4294. """
  4295. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4296. :return:
  4297. """
  4298. def initialize_geometry(obj_init, app_obj):
  4299. apertures = {}
  4300. apid = 0
  4301. apertures[str(apid)] = {}
  4302. apertures[str(apid)]['geometry'] = []
  4303. for obj_orig in obj.solid_geometry:
  4304. new_elem = {}
  4305. new_elem['solid'] = obj_orig
  4306. try:
  4307. new_elem['follow'] = obj_orig.exterior
  4308. except AttributeError:
  4309. pass
  4310. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4311. apertures[str(apid)]['size'] = 0.0
  4312. apertures[str(apid)]['type'] = 'C'
  4313. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4314. obj_init.apertures = deepcopy(apertures)
  4315. if not obj_init.apertures:
  4316. app_obj.log("convert_any2gerber() failed")
  4317. return 'fail'
  4318. def initialize_excellon(obj_init, app_obj):
  4319. apertures = {}
  4320. apid = 10
  4321. for tool in obj.tools:
  4322. apertures[str(apid)] = {}
  4323. apertures[str(apid)]['geometry'] = []
  4324. for geo in obj.tools[tool]['solid_geometry']:
  4325. new_el = {}
  4326. new_el['solid'] = geo
  4327. new_el['follow'] = geo.exterior
  4328. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4329. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4330. apertures[str(apid)]['type'] = 'C'
  4331. apid += 1
  4332. # create solid_geometry
  4333. solid_geometry = []
  4334. for apid in apertures:
  4335. for geo_el in apertures[apid]['geometry']:
  4336. solid_geometry.append(geo_el['solid'])
  4337. solid_geometry = MultiPolygon(solid_geometry)
  4338. solid_geometry = solid_geometry.buffer(0.0000001)
  4339. obj_init.solid_geometry = deepcopy(solid_geometry)
  4340. obj_init.apertures = deepcopy(apertures)
  4341. if not obj_init.apertures:
  4342. app_obj.log("convert_any2gerber() failed")
  4343. return 'fail'
  4344. if not self.collection.get_selected():
  4345. log.warning("App.convert_any2gerber --> No object selected")
  4346. self.inform.emit('[WARNING_NOTCL] %s' %
  4347. _("No object is selected. Select an object and try again."))
  4348. return
  4349. for obj in self.collection.get_selected():
  4350. obj_name = obj.options["name"]
  4351. try:
  4352. if obj.kind == 'excellon':
  4353. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4354. elif obj.kind == 'geometry':
  4355. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4356. else:
  4357. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4358. except Exception as e:
  4359. return "Operation failed: %s" % str(e)
  4360. def convert_any2excellon(self):
  4361. """
  4362. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4363. :return:
  4364. """
  4365. def initialize_geometry(obj_init, app_obj):
  4366. tools = {}
  4367. tooluid = 1
  4368. obj_init.solid_geometry = []
  4369. for geo in obj.solid_geometry:
  4370. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4371. continue
  4372. minx, miny, maxx, maxy = geo.bounds
  4373. new_dia = min([maxx-minx, maxy-miny])
  4374. new_drill = geo.centroid
  4375. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4376. current_tooldias = []
  4377. if tools:
  4378. for tool in tools:
  4379. if tools[tool] and 'tooldia' in tools[tool]:
  4380. current_tooldias.append(tools[tool]['tooldia'])
  4381. if new_dia in current_tooldias:
  4382. digits = app_obj.decimals
  4383. for tool in tools:
  4384. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4385. tools[tool]['drills'].append(new_drill)
  4386. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4387. else:
  4388. tools[tooluid] = {}
  4389. tools[tooluid]['tooldia'] = new_dia
  4390. tools[tooluid]['drills'] = [new_drill]
  4391. tools[tooluid]['slots'] = []
  4392. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4393. tooluid += 1
  4394. try:
  4395. obj_init.solid_geometry.append(new_drill_geo)
  4396. except (TypeError, AttributeError):
  4397. obj_init.solid_geometry = [new_drill_geo]
  4398. obj_init.tools = deepcopy(tools)
  4399. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4400. if not obj_init.solid_geometry:
  4401. return 'fail'
  4402. def initialize_gerber(obj_init, app_obj):
  4403. tools = {}
  4404. tooluid = 1
  4405. digits = app_obj.decimals
  4406. obj_init.solid_geometry = []
  4407. for apid in obj.apertures:
  4408. if 'geometry' in obj.apertures[apid]:
  4409. for geo_dict in obj.apertures[apid]['geometry']:
  4410. if 'follow' in geo_dict:
  4411. if isinstance(geo_dict['follow'], Point):
  4412. geo = geo_dict['solid']
  4413. minx, miny, maxx, maxy = geo.bounds
  4414. new_dia = min([maxx - minx, maxy - miny])
  4415. new_drill = geo.centroid
  4416. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4417. current_tooldias = []
  4418. if tools:
  4419. for tool in tools:
  4420. if tools[tool] and 'tooldia' in tools[tool]:
  4421. current_tooldias.append(
  4422. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4423. )
  4424. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4425. if formatted_new_dia in current_tooldias:
  4426. for tool in tools:
  4427. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4428. if new_drill not in tools[tool]['drills']:
  4429. tools[tool]['drills'].append(new_drill)
  4430. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4431. else:
  4432. tools[tooluid] = {}
  4433. tools[tooluid]['tooldia'] = new_dia
  4434. tools[tooluid]['drills'] = [new_drill]
  4435. tools[tooluid]['slots'] = []
  4436. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4437. tooluid += 1
  4438. try:
  4439. obj_init.solid_geometry.append(new_drill_geo)
  4440. except (TypeError, AttributeError):
  4441. obj_init.solid_geometry = [new_drill_geo]
  4442. elif isinstance(geo_dict['follow'], LineString):
  4443. geo_coords = list(geo_dict['follow'].coords)
  4444. # slots can have only a start and stop point and no intermediate points
  4445. if len(geo_coords) != 2:
  4446. continue
  4447. geo = geo_dict['solid']
  4448. try:
  4449. new_dia = obj.apertures[apid]['size']
  4450. except Exception:
  4451. continue
  4452. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4453. new_slot_geo = geo
  4454. current_tooldias = []
  4455. if tools:
  4456. for tool in tools:
  4457. if tools[tool] and 'tooldia' in tools[tool]:
  4458. current_tooldias.append(
  4459. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4460. )
  4461. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4462. for tool in tools:
  4463. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4464. '%.*f' % (self.decimals, new_dia)):
  4465. if new_slot not in tools[tool]['slots']:
  4466. tools[tool]['slots'].append(new_slot)
  4467. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4468. else:
  4469. tools[tooluid] = {}
  4470. tools[tooluid]['tooldia'] = new_dia
  4471. tools[tooluid]['drills'] = []
  4472. tools[tooluid]['slots'] = [new_slot]
  4473. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4474. tooluid += 1
  4475. try:
  4476. obj_init.solid_geometry.append(new_slot_geo)
  4477. except (TypeError, AttributeError):
  4478. obj_init.solid_geometry = [new_slot_geo]
  4479. obj_init.tools = deepcopy(tools)
  4480. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4481. if not obj_init.solid_geometry:
  4482. return 'fail'
  4483. if not self.collection.get_selected():
  4484. log.warning("App.convert_any2excellon--> No object selected")
  4485. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4486. return
  4487. for obj in self.collection.get_selected():
  4488. obj_name = obj.options["name"]
  4489. try:
  4490. if obj.kind == 'gerber':
  4491. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4492. elif obj.kind == 'geometry':
  4493. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4494. else:
  4495. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4496. except Exception as e:
  4497. return "Operation failed: %s" % str(e)
  4498. def abort_all_tasks(self):
  4499. """
  4500. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4501. on the first possible occasion.
  4502. :return:
  4503. """
  4504. if self.abort_flag is False:
  4505. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4506. self.abort_flag = True
  4507. self.cleanup.emit()
  4508. def app_is_idle(self):
  4509. if self.abort_flag:
  4510. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4511. self.abort_flag = False
  4512. def on_selectall(self):
  4513. """
  4514. Will draw a selection box shape around the selected objects.
  4515. :return:
  4516. """
  4517. self.defaults.report_usage("on_selectall()")
  4518. # delete the possible selection box around a possible selected object
  4519. self.delete_selection_shape()
  4520. for name in self.collection.get_names():
  4521. self.collection.set_active(name)
  4522. curr_sel_obj = self.collection.get_by_name(name)
  4523. # create the selection box around the selected object
  4524. if self.defaults['global_selection_shape'] is True:
  4525. self.draw_selection_shape(curr_sel_obj)
  4526. def on_toggle_preferences(self):
  4527. pref_open = False
  4528. for idx in range(self.ui.plot_tab_area.count()):
  4529. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4530. pref_open = True
  4531. if pref_open:
  4532. for idx in range(self.ui.plot_tab_area.count()):
  4533. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4534. self.ui.plot_tab_area.removeTab(idx)
  4535. break
  4536. self.ui.pref_status_label.setStyleSheet("")
  4537. else:
  4538. self.on_preferences()
  4539. def on_preferences(self):
  4540. """
  4541. Adds the Preferences in a Tab in Plot Area
  4542. :return:
  4543. """
  4544. # add the tab if it was closed
  4545. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4546. # delete the absolute and relative position and messages in the infobar
  4547. # self.ui.position_label.setText("")
  4548. # self.ui.rel_position_label.setText("")
  4549. # hide coordinates toolbars in the infobar while in DB
  4550. self.ui.coords_toolbar.hide()
  4551. self.ui.delta_coords_toolbar.hide()
  4552. # Switch plot_area to preferences page
  4553. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4554. # self.ui.show()
  4555. self.ui.pref_status_label.setStyleSheet("""
  4556. QLabel
  4557. {
  4558. color: black;
  4559. background-color: lightseagreen;
  4560. }
  4561. """
  4562. )
  4563. # detect changes in the preferences
  4564. for idx in range(self.ui.pref_tab_area.count()):
  4565. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4566. try:
  4567. try:
  4568. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4569. except (TypeError, AttributeError):
  4570. pass
  4571. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4572. except AttributeError:
  4573. pass
  4574. try:
  4575. try:
  4576. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4577. except (TypeError, AttributeError):
  4578. pass
  4579. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4580. except AttributeError:
  4581. pass
  4582. try:
  4583. try:
  4584. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4585. except (TypeError, AttributeError):
  4586. pass
  4587. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4588. except AttributeError:
  4589. pass
  4590. try:
  4591. try:
  4592. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4593. except (TypeError, AttributeError):
  4594. pass
  4595. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4596. except AttributeError:
  4597. pass
  4598. try:
  4599. try:
  4600. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4601. except (TypeError, AttributeError):
  4602. pass
  4603. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4604. except AttributeError:
  4605. pass
  4606. def on_tools_database(self, source='app'):
  4607. """
  4608. Adds the Tools Database in a Tab in Plot Area.
  4609. :return:
  4610. """
  4611. filename = self.tools_database_path()
  4612. # load the database tools from the file
  4613. try:
  4614. with open(filename) as f:
  4615. __ = f.read()
  4616. except Exception as eros:
  4617. self.log.debug("The tools DB file is not loaded: %s" % str(eros))
  4618. log.error("Could not access tools DB file. The file may be locked,\n"
  4619. "not existing or doesn't have the read permissions.\n"
  4620. "Check to see if exists, it should be here: %s\n"
  4621. "It may help to reboot the app, it will try to recreate it if it's missing." % self.data_path)
  4622. self.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  4623. return 'fail'
  4624. for idx in range(self.ui.plot_tab_area.count()):
  4625. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4626. # there can be only one instance of Tools Database at one time
  4627. return
  4628. if source == 'app':
  4629. self.tools_db_tab = ToolsDB2(
  4630. app=self,
  4631. parent=self.ui,
  4632. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4633. )
  4634. elif source == 'ncc':
  4635. self.tools_db_tab = ToolsDB2(
  4636. app=self,
  4637. parent=self.ui,
  4638. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4639. )
  4640. elif source == 'paint':
  4641. self.tools_db_tab = ToolsDB2(
  4642. app=self,
  4643. parent=self.ui,
  4644. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4645. )
  4646. elif source == 'iso':
  4647. self.tools_db_tab = ToolsDB2(
  4648. app=self,
  4649. parent=self.ui,
  4650. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4651. )
  4652. elif source == 'cutout':
  4653. self.tools_db_tab = ToolsDB2(
  4654. app=self,
  4655. parent=self.ui,
  4656. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4657. )
  4658. # add the tab if it was closed
  4659. try:
  4660. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4661. self.tools_db_tab.setObjectName("database_tab")
  4662. except Exception as e:
  4663. self.log.debug("App.on_tools_database() --> %s" % str(e))
  4664. return
  4665. # delete the absolute and relative position and messages in the infobar
  4666. # self.ui.position_label.setText("")
  4667. # self.ui.rel_position_label.setText("")
  4668. # hide coordinates toolbars in the infobar while in DB
  4669. self.ui.coords_toolbar.hide()
  4670. self.ui.delta_coords_toolbar.hide()
  4671. # Switch plot_area to preferences page
  4672. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4673. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4674. self.tools_db_tab.ui_connect()
  4675. def on_geometry_tool_add_from_db_executed(self, tool):
  4676. """
  4677. Here add the tool from DB in the selected geometry object.
  4678. :return:
  4679. """
  4680. tool_from_db = deepcopy(tool)
  4681. obj = self.collection.get_active()
  4682. if obj.kind == 'geometry':
  4683. if tool['data']['tool_target'] not in [0, 1]: # General, Milling Type
  4684. # close the tab and delete it
  4685. for idx in range(self.ui.plot_tab_area.count()):
  4686. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4687. wdg = self.ui.plot_tab_area.widget(idx)
  4688. wdg.deleteLater()
  4689. self.ui.plot_tab_area.removeTab(idx)
  4690. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4691. return
  4692. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4693. # close the tab and delete it
  4694. for idx in range(self.ui.plot_tab_area.count()):
  4695. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4696. wdg = self.ui.plot_tab_area.widget(idx)
  4697. wdg.deleteLater()
  4698. self.ui.plot_tab_area.removeTab(idx)
  4699. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4700. elif obj.kind == 'gerber':
  4701. if tool['data']['tool_target'] not in [0, 3]: # General, Isolation Type
  4702. # close the tab and delete it
  4703. for idx in range(self.ui.plot_tab_area.count()):
  4704. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4705. wdg = self.ui.plot_tab_area.widget(idx)
  4706. wdg.deleteLater()
  4707. self.ui.plot_tab_area.removeTab(idx)
  4708. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4709. return
  4710. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4711. # close the tab and delete it
  4712. for idx in range(self.ui.plot_tab_area.count()):
  4713. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4714. wdg = self.ui.plot_tab_area.widget(idx)
  4715. wdg.deleteLater()
  4716. self.ui.plot_tab_area.removeTab(idx)
  4717. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4718. else:
  4719. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4720. def on_plot_area_tab_closed(self, tab_obj_name):
  4721. """
  4722. Executed whenever a QTab is closed in the Plot Area.
  4723. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4724. :return:
  4725. """
  4726. if tab_obj_name == "preferences_tab":
  4727. self.preferencesUiManager.on_close_preferences_tab()
  4728. elif tab_obj_name == "database_tab":
  4729. # disconnect the signals from the table widget in tab
  4730. self.tools_db_tab.ui_disconnect()
  4731. if self.tools_db_changed_flag is True:
  4732. msgbox = QtWidgets.QMessageBox()
  4733. msgbox.setText(_("One or more Tools are edited.\n"
  4734. "Do you want to update the Tools Database?"))
  4735. msgbox.setWindowTitle(_("Save Tools Database"))
  4736. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4737. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4738. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4739. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4740. msgbox.setDefaultButton(bt_yes)
  4741. msgbox.exec_()
  4742. response = msgbox.clickedButton()
  4743. if response == bt_yes:
  4744. self.tools_db_tab.on_save_tools_db()
  4745. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4746. else:
  4747. self.tools_db_changed_flag = False
  4748. self.inform.emit('')
  4749. return
  4750. self.tools_db_tab.deleteLater()
  4751. elif tab_obj_name == "text_editor_tab":
  4752. self.toggle_codeeditor = False
  4753. elif tab_obj_name == "bookmarks_tab":
  4754. self.book_dialog_tab.rebuild_actions()
  4755. self.book_dialog_tab.deleteLater()
  4756. else:
  4757. pass
  4758. # restore the coords toolbars
  4759. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4760. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4761. def on_flipy(self):
  4762. """
  4763. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4764. :return:
  4765. """
  4766. self.defaults.report_usage("on_flipy()")
  4767. obj_list = self.collection.get_selected()
  4768. xminlist = []
  4769. yminlist = []
  4770. xmaxlist = []
  4771. ymaxlist = []
  4772. if not obj_list:
  4773. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4774. else:
  4775. try:
  4776. # first get a bounding box to fit all
  4777. for obj in obj_list:
  4778. xmin, ymin, xmax, ymax = obj.bounds()
  4779. xminlist.append(xmin)
  4780. yminlist.append(ymin)
  4781. xmaxlist.append(xmax)
  4782. ymaxlist.append(ymax)
  4783. # get the minimum x,y and maximum x,y for all objects selected
  4784. xminimal = min(xminlist)
  4785. yminimal = min(yminlist)
  4786. xmaximal = max(xmaxlist)
  4787. ymaximal = max(ymaxlist)
  4788. px = 0.5 * (xminimal + xmaximal)
  4789. py = 0.5 * (yminimal + ymaximal)
  4790. # execute mirroring
  4791. for obj in obj_list:
  4792. obj.mirror('X', [px, py])
  4793. obj.plot()
  4794. self.app_obj.object_changed.emit(obj)
  4795. self.inform.emit('[success] %s' %
  4796. _("Flip on Y axis done."))
  4797. except Exception as e:
  4798. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4799. return
  4800. def on_flipx(self):
  4801. """
  4802. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4803. :return:
  4804. """
  4805. self.defaults.report_usage("on_flipx()")
  4806. obj_list = self.collection.get_selected()
  4807. xminlist = []
  4808. yminlist = []
  4809. xmaxlist = []
  4810. ymaxlist = []
  4811. if not obj_list:
  4812. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on X axis."))
  4813. else:
  4814. try:
  4815. # first get a bounding box to fit all
  4816. for obj in obj_list:
  4817. xmin, ymin, xmax, ymax = obj.bounds()
  4818. xminlist.append(xmin)
  4819. yminlist.append(ymin)
  4820. xmaxlist.append(xmax)
  4821. ymaxlist.append(ymax)
  4822. # get the minimum x,y and maximum x,y for all objects selected
  4823. xminimal = min(xminlist)
  4824. yminimal = min(yminlist)
  4825. xmaximal = max(xmaxlist)
  4826. ymaximal = max(ymaxlist)
  4827. px = 0.5 * (xminimal + xmaximal)
  4828. py = 0.5 * (yminimal + ymaximal)
  4829. # execute mirroring
  4830. for obj in obj_list:
  4831. obj.mirror('Y', [px, py])
  4832. obj.plot()
  4833. self.app_obj.object_changed.emit(obj)
  4834. self.inform.emit('[success] %s' %
  4835. _("Flip on X axis done."))
  4836. except Exception as e:
  4837. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4838. return
  4839. def on_rotate(self, silent=False, preset=None):
  4840. """
  4841. Executed when Options -> Rotate Selection menu entry is clicked.
  4842. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4843. :param preset: A value to be used as predefined angle for rotation.
  4844. :return:
  4845. """
  4846. self.defaults.report_usage("on_rotate()")
  4847. obj_list = self.collection.get_selected()
  4848. xminlist = []
  4849. yminlist = []
  4850. xmaxlist = []
  4851. ymaxlist = []
  4852. if not obj_list:
  4853. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4854. else:
  4855. if silent is False:
  4856. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4857. min=-360, max=360, decimals=4,
  4858. init_val=float(self.defaults['tools_transform_rotate']))
  4859. num, ok = rotatebox.get_value()
  4860. else:
  4861. num = preset
  4862. ok = True
  4863. if ok:
  4864. try:
  4865. # first get a bounding box to fit all
  4866. for obj in obj_list:
  4867. xmin, ymin, xmax, ymax = obj.bounds()
  4868. xminlist.append(xmin)
  4869. yminlist.append(ymin)
  4870. xmaxlist.append(xmax)
  4871. ymaxlist.append(ymax)
  4872. # get the minimum x,y and maximum x,y for all objects selected
  4873. xminimal = min(xminlist)
  4874. yminimal = min(yminlist)
  4875. xmaximal = max(xmaxlist)
  4876. ymaximal = max(ymaxlist)
  4877. px = 0.5 * (xminimal + xmaximal)
  4878. py = 0.5 * (yminimal + ymaximal)
  4879. for sel_obj in obj_list:
  4880. sel_obj.rotate(-float(num), point=(px, py))
  4881. sel_obj.plot()
  4882. self.app_obj.object_changed.emit(sel_obj)
  4883. self.inform.emit('[success] %s' % _("Rotation done."))
  4884. except Exception as e:
  4885. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4886. return
  4887. def on_skewx(self):
  4888. """
  4889. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4890. :return:
  4891. """
  4892. self.defaults.report_usage("on_skewx()")
  4893. obj_list = self.collection.get_selected()
  4894. xminlist = []
  4895. yminlist = []
  4896. if not obj_list:
  4897. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4898. else:
  4899. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4900. min=-360, max=360, decimals=4,
  4901. init_val=float(self.defaults['tools_transform_skew_x']))
  4902. num, ok = skewxbox.get_value()
  4903. if ok:
  4904. # first get a bounding box to fit all
  4905. for obj in obj_list:
  4906. xmin, ymin, xmax, ymax = obj.bounds()
  4907. xminlist.append(xmin)
  4908. yminlist.append(ymin)
  4909. # get the minimum x,y and maximum x,y for all objects selected
  4910. xminimal = min(xminlist)
  4911. yminimal = min(yminlist)
  4912. for obj in obj_list:
  4913. obj.skew(num, 0, point=(xminimal, yminimal))
  4914. obj.plot()
  4915. self.app_obj.object_changed.emit(obj)
  4916. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4917. def on_skewy(self):
  4918. """
  4919. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4920. :return:
  4921. """
  4922. self.defaults.report_usage("on_skewy()")
  4923. obj_list = self.collection.get_selected()
  4924. xminlist = []
  4925. yminlist = []
  4926. if not obj_list:
  4927. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4928. else:
  4929. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4930. min=-360, max=360, decimals=4,
  4931. init_val=float(self.defaults['tools_transform_skew_y']))
  4932. num, ok = skewybox.get_value()
  4933. if ok:
  4934. # first get a bounding box to fit all
  4935. for obj in obj_list:
  4936. xmin, ymin, xmax, ymax = obj.bounds()
  4937. xminlist.append(xmin)
  4938. yminlist.append(ymin)
  4939. # get the minimum x,y and maximum x,y for all objects selected
  4940. xminimal = min(xminlist)
  4941. yminimal = min(yminlist)
  4942. for obj in obj_list:
  4943. obj.skew(0, num, point=(xminimal, yminimal))
  4944. obj.plot()
  4945. self.app_obj.object_changed.emit(obj)
  4946. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4947. def on_plots_updated(self):
  4948. """
  4949. Callback used to report when the plots have changed.
  4950. Adjust axes and zooms to fit.
  4951. :return: None
  4952. """
  4953. if self.is_legacy is False:
  4954. self.plotcanvas.update()
  4955. else:
  4956. self.plotcanvas.auto_adjust_axes()
  4957. self.on_zoom_fit()
  4958. self.collection.update_view()
  4959. # self.inform.emit(_("Plots updated ..."))
  4960. def on_toolbar_replot(self):
  4961. """
  4962. Callback for toolbar button. Re-plots all objects.
  4963. :return: None
  4964. """
  4965. self.log.debug("on_toolbar_replot()")
  4966. try:
  4967. obj = self.collection.get_active()
  4968. if obj:
  4969. obj.read_form()
  4970. else:
  4971. self.on_zoom_fit()
  4972. except AttributeError as e:
  4973. self.log.debug("on_toolbar_replot() -> %s" % str(e))
  4974. pass
  4975. self.plot_all()
  4976. def grid_status(self):
  4977. return True if self.ui.grid_snap_btn.isChecked() else False
  4978. def populate_cmenu_grids(self):
  4979. units = self.defaults['units'].lower()
  4980. # for act in self.ui.cmenu_gridmenu.actions():
  4981. # act.triggered.disconnect()
  4982. self.ui.cmenu_gridmenu.clear()
  4983. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4984. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4985. _("Grid On/Off"))
  4986. grid_toggle.setCheckable(True)
  4987. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4988. self.ui.cmenu_gridmenu.addSeparator()
  4989. for grid in sorted_list:
  4990. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4991. "%s" % str(grid))
  4992. action.triggered.connect(self.set_grid)
  4993. self.ui.cmenu_gridmenu.addSeparator()
  4994. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4995. _("Add"))
  4996. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4997. _("Delete"))
  4998. grid_add.triggered.connect(self.on_grid_add)
  4999. grid_delete.triggered.connect(self.on_grid_delete)
  5000. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5001. def set_grid(self):
  5002. menu_action = self.sender()
  5003. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5004. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5005. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5006. def on_grid_add(self):
  5007. # ## Current application units in lower Case
  5008. units = self.defaults['units'].lower()
  5009. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5010. text=_('Enter a Grid Value:'),
  5011. min=0.0000, max=99.9999, decimals=4)
  5012. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5013. val, ok = grid_add_popup.get_value()
  5014. if ok:
  5015. if float(val) == 0:
  5016. self.inform.emit('[WARNING_NOTCL] %s' %
  5017. _("Please enter a grid value with non-zero value, in Float format."))
  5018. return
  5019. else:
  5020. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5021. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5022. self.inform.emit('[success] %s...' % _("New Grid added"))
  5023. else:
  5024. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5025. else:
  5026. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5027. def on_grid_delete(self):
  5028. # ## Current application units in lower Case
  5029. units = self.defaults['units'].lower()
  5030. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5031. text='Enter a Grid Value:',
  5032. min=0.0000, max=99.9999, decimals=4)
  5033. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5034. val, ok = grid_del_popup.get_value()
  5035. if ok:
  5036. if float(val) == 0:
  5037. self.inform.emit('[WARNING_NOTCL] %s' %
  5038. _("Please enter a grid value with non-zero value, in Float format."))
  5039. return
  5040. else:
  5041. try:
  5042. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5043. except ValueError:
  5044. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5045. return
  5046. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5047. else:
  5048. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5049. def on_shortcut_list(self):
  5050. self.defaults.report_usage("on_shortcut_list()")
  5051. # add the tab if it was closed
  5052. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5053. # delete the absolute and relative position and messages in the infobar
  5054. # self.ui.position_label.setText("")
  5055. # self.ui.rel_position_label.setText("")
  5056. # hide coordinates toolbars in the infobar while in DB
  5057. self.ui.coords_toolbar.hide()
  5058. self.ui.delta_coords_toolbar.hide()
  5059. # Switch plot_area to preferences page
  5060. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5061. # self.ui.show()
  5062. def on_select_tab(self, name):
  5063. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5064. if self.ui.splitter.sizes()[0] == 0:
  5065. self.ui.splitter.setSizes([1, 1])
  5066. else:
  5067. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5068. self.ui.splitter.setSizes([0, 1])
  5069. if name == 'project':
  5070. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5071. elif name == 'properties':
  5072. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5073. elif name == 'tool':
  5074. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5075. def on_copy_name(self):
  5076. self.defaults.report_usage("on_copy_name()")
  5077. obj = self.collection.get_active()
  5078. try:
  5079. name = obj.options["name"]
  5080. except AttributeError:
  5081. self.log.debug("on_copy_name() --> No object selected to copy it's name")
  5082. self.inform.emit('[WARNING_NOTCL] %s' %
  5083. _(" No object selected to copy it's name"))
  5084. return
  5085. self.clipboard.setText(name)
  5086. self.inform.emit(_("Name copied on clipboard ..."))
  5087. def on_mouse_click_over_plot(self, event):
  5088. """
  5089. Default actions are:
  5090. :param event: Contains information about the event, like which button
  5091. was clicked, the pixel coordinates and the axes coordinates.
  5092. :return: None
  5093. """
  5094. self.pos = []
  5095. if self.is_legacy is False:
  5096. event_pos = event.pos
  5097. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5098. # # Set the mouse button for panning
  5099. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5100. else:
  5101. event_pos = (event.xdata, event.ydata)
  5102. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5103. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5104. # So it can receive key presses
  5105. self.plotcanvas.native.setFocus()
  5106. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5107. if self.grid_status():
  5108. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5109. else:
  5110. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5111. try:
  5112. if event.button == 1:
  5113. # Reset here the relative coordinates so there is a new reference on the click position
  5114. if self.rel_point1 is None:
  5115. self.rel_point1 = self.pos
  5116. else:
  5117. self.rel_point2 = copy(self.rel_point1)
  5118. self.rel_point1 = self.pos
  5119. self.on_mouse_move_over_plot(event, origin_click=True)
  5120. except Exception as e:
  5121. self.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5122. def on_mouse_double_click_over_plot(self, event):
  5123. if event.button == 1:
  5124. self.doubleclick = True
  5125. def on_mouse_move_over_plot(self, event, origin_click=None):
  5126. """
  5127. Callback for the mouse motion event over the plot.
  5128. :param event: Contains information about the event.
  5129. :param origin_click
  5130. :return: None
  5131. """
  5132. if self.is_legacy is False:
  5133. event_pos = event.pos
  5134. if self.defaults["global_pan_button"] == '2':
  5135. pan_button = 2
  5136. else:
  5137. pan_button = 3
  5138. self.event_is_dragging = event.is_dragging
  5139. else:
  5140. event_pos = (event.xdata, event.ydata)
  5141. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5142. if self.defaults["global_pan_button"] == '2':
  5143. pan_button = 3
  5144. else:
  5145. pan_button = 2
  5146. self.event_is_dragging = self.plotcanvas.is_dragging
  5147. # So it can receive key presses but not when the Tcl Shell is active
  5148. if not self.ui.shell_dock.isVisible():
  5149. if not self.plotcanvas.native.hasFocus():
  5150. self.plotcanvas.native.setFocus()
  5151. self.pos_jump = event_pos
  5152. self.ui.popMenu.mouse_is_panning = False
  5153. if origin_click is None:
  5154. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5155. if event.button == pan_button and self.event_is_dragging == 1:
  5156. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5157. if self.ui.popMenu.popup_active:
  5158. self.ui.popMenu.popup_active = False
  5159. return
  5160. self.ui.popMenu.mouse_is_panning = True
  5161. return
  5162. if self.rel_point1 is not None:
  5163. try: # May fail in case mouse not within axes
  5164. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5165. if pos_canvas[0] is None or pos_canvas[1] is None:
  5166. return
  5167. if self.grid_status():
  5168. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5169. # Update cursor
  5170. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5171. symbol='++', edge_color=self.cursor_color_3D,
  5172. edge_width=self.defaults["global_cursor_width"],
  5173. size=self.defaults["global_cursor_size"])
  5174. else:
  5175. pos = (pos_canvas[0], pos_canvas[1])
  5176. self.dx = pos[0] - float(self.rel_point1[0])
  5177. self.dy = pos[1] - float(self.rel_point1[1])
  5178. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5179. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5180. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5181. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5182. units = self.defaults["units"].lower()
  5183. self.plotcanvas.text_hud.text = \
  5184. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5185. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5186. self.mouse = [pos[0], pos[1]]
  5187. if self.defaults['global_selection_shape'] is False:
  5188. self.selection_type = None
  5189. return
  5190. # if the mouse is moved and the LMB is clicked then the action is a selection
  5191. if self.event_is_dragging == 1 and event.button == 1:
  5192. self.delete_selection_shape()
  5193. if self.dx < 0:
  5194. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5195. face_color=self.defaults['global_alt_sel_fill'])
  5196. self.selection_type = False
  5197. elif self.dx >= 0:
  5198. self.draw_moving_selection_shape(self.pos, pos)
  5199. self.selection_type = True
  5200. else:
  5201. self.selection_type = None
  5202. else:
  5203. self.selection_type = None
  5204. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5205. if self.defaults['global_hover']:
  5206. for obj in self.collection.get_list():
  5207. try:
  5208. # select the object(s) only if it is enabled (plotted)
  5209. if obj.options['plot']:
  5210. if obj not in self.collection.get_selected():
  5211. poly_obj = Polygon(
  5212. [(obj.options['xmin'], obj.options['ymin']),
  5213. (obj.options['xmax'], obj.options['ymin']),
  5214. (obj.options['xmax'], obj.options['ymax']),
  5215. (obj.options['xmin'], obj.options['ymax'])]
  5216. )
  5217. if Point(pos).within(poly_obj):
  5218. if obj.isHovering is False:
  5219. obj.isHovering = True
  5220. obj.notHovering = True
  5221. # create the selection box around the selected object
  5222. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5223. else:
  5224. if obj.notHovering is True:
  5225. obj.notHovering = False
  5226. obj.isHovering = False
  5227. self.delete_hover_shape()
  5228. except Exception:
  5229. # the Exception here will happen if we try to select on screen and we have an
  5230. # newly (and empty) just created Geometry or Excellon object that do not have the
  5231. # xmin, xmax, ymin, ymax options.
  5232. # In this case poly_obj creation (see above) will fail
  5233. pass
  5234. except Exception as e:
  5235. self.log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5236. self.ui.position_label.setText("")
  5237. self.ui.rel_position_label.setText("")
  5238. self.mouse = None
  5239. def on_mouse_click_release_over_plot(self, event):
  5240. """
  5241. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5242. and has been registered in ''self.__init__()''.
  5243. :param event: contains information about the event.
  5244. :return:
  5245. """
  5246. if self.is_legacy is False:
  5247. event_pos = event.pos
  5248. right_button = 2
  5249. else:
  5250. event_pos = (event.xdata, event.ydata)
  5251. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5252. right_button = 3
  5253. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5254. if self.grid_status():
  5255. try:
  5256. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5257. except TypeError:
  5258. return
  5259. else:
  5260. pos = (pos_canvas[0], pos_canvas[1])
  5261. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5262. # canvas menu
  5263. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5264. self.ui.popMenu.mouse_is_panning = False
  5265. self.cursor = QtGui.QCursor()
  5266. self.populate_cmenu_grids()
  5267. self.ui.popMenu.popup(self.cursor.pos())
  5268. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5269. # selection and then select a type of selection ("enclosing" or "touching")
  5270. if event.button == 1: # left click
  5271. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5272. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5273. if modifiers == QtCore.Qt.ShiftModifier:
  5274. # do not auto open the Project Tab
  5275. self.click_noproject = True
  5276. self.clipboard.setText(
  5277. self.defaults["global_point_clipboard_format"] %
  5278. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5279. )
  5280. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5281. return
  5282. if self.doubleclick is True:
  5283. self.doubleclick = False
  5284. if self.collection.get_selected():
  5285. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5286. if self.ui.splitter.sizes()[0] == 0:
  5287. self.ui.splitter.setSizes([1, 1])
  5288. try:
  5289. # delete the selection shape(S) as it may be in the way
  5290. self.delete_selection_shape()
  5291. self.delete_hover_shape()
  5292. except Exception as e:
  5293. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5294. return
  5295. else:
  5296. # WORKAROUND for LEGACY MODE
  5297. if self.is_legacy is True:
  5298. # if there is no move on canvas then we have no dragging selection
  5299. if self.dx == 0 or self.dy == 0:
  5300. self.selection_type = None
  5301. if self.selection_type is not None:
  5302. try:
  5303. self.selection_area_handler(self.pos, pos, self.selection_type)
  5304. self.selection_type = None
  5305. except Exception as e:
  5306. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5307. return
  5308. else:
  5309. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5310. if key_modifier == QtCore.Qt.ShiftModifier:
  5311. mod_key = 'Shift'
  5312. elif key_modifier == QtCore.Qt.ControlModifier:
  5313. mod_key = 'Control'
  5314. else:
  5315. mod_key = None
  5316. try:
  5317. if self.command_active is None:
  5318. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5319. # deselect, and if it's not selected then it will be selected
  5320. # If there is no active command (self.command_active is None) then we check if we clicked
  5321. # on a object by checking the bounding limits against mouse click position
  5322. if mod_key == self.defaults["global_mselect_key"]:
  5323. self.select_objects(key='multisel')
  5324. else:
  5325. # If there is no active command (self.command_active is None) then we check if
  5326. # we clicked on a object by checking the bounding limits against mouse click position
  5327. self.select_objects()
  5328. self.delete_hover_shape()
  5329. except Exception as e:
  5330. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5331. return
  5332. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5333. """
  5334. :param start_pos: mouse position when the selection LMB click was done
  5335. :param end_pos: mouse position when the left mouse button is released
  5336. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5337. :return:
  5338. """
  5339. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5340. # delete previous selection shape
  5341. self.delete_selection_shape()
  5342. # make all objects inactive
  5343. self.collection.set_all_inactive()
  5344. for obj in self.collection.get_list():
  5345. try:
  5346. # select the object(s) only if it is enabled (plotted)
  5347. if obj.options['plot']:
  5348. # it's a line without area
  5349. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5350. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5351. # it's a geometry with area
  5352. else:
  5353. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5354. (obj.options['xmax'], obj.options['ymin']),
  5355. (obj.options['xmax'], obj.options['ymax']),
  5356. (obj.options['xmin'], obj.options['ymax'])])
  5357. if poly_obj.is_empty or not poly_obj.is_valid:
  5358. continue
  5359. if sel_type is True:
  5360. if poly_obj.within(poly_selection):
  5361. # create the selection box around the selected object
  5362. if self.defaults['global_selection_shape'] is True:
  5363. self.draw_selection_shape(obj)
  5364. self.collection.set_active(obj.options['name'])
  5365. else:
  5366. if poly_selection.intersects(poly_obj):
  5367. # create the selection box around the selected object
  5368. if self.defaults['global_selection_shape'] is True:
  5369. self.draw_selection_shape(obj)
  5370. self.collection.set_active(obj.options['name'])
  5371. obj.selection_shape_drawn = True
  5372. except Exception as e:
  5373. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5374. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5375. # In this case poly_obj creation (see above) will fail
  5376. self.log.debug("App.selection_area_handler() --> %s" % str(e))
  5377. def select_objects(self, key=None):
  5378. """
  5379. Will select objects clicked on canvas
  5380. :param key: for future use in cumulative selection
  5381. :return:
  5382. """
  5383. # list where we store the overlapped objects under our mouse left click position
  5384. if key is None:
  5385. self.objects_under_the_click_list = []
  5386. # Populate the list with the overlapped objects on the click position
  5387. curr_x, curr_y = self.pos
  5388. for obj in self.all_objects_list:
  5389. # ScriptObject and DocumentObject objects can't be selected
  5390. if obj.kind == 'script' or obj.kind == 'document':
  5391. continue
  5392. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5393. continue
  5394. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5395. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5396. if obj.options['name'] not in self.objects_under_the_click_list:
  5397. if obj.options['plot']:
  5398. # add objects to the objects_under_the_click list only if the object is plotted
  5399. # (active and not disabled)
  5400. self.objects_under_the_click_list.append(obj.options['name'])
  5401. try:
  5402. if self.objects_under_the_click_list:
  5403. curr_sel_obj = self.collection.get_active()
  5404. # case when there is only an object under the click and we toggle it
  5405. if len(self.objects_under_the_click_list) == 1:
  5406. if curr_sel_obj is None:
  5407. self.collection.set_active(self.objects_under_the_click_list[0])
  5408. curr_sel_obj = self.collection.get_active()
  5409. # create the selection box around the selected object
  5410. if self.defaults['global_selection_shape'] is True:
  5411. self.draw_selection_shape(curr_sel_obj)
  5412. curr_sel_obj.selection_shape_drawn = True
  5413. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5414. self.collection.on_objects_selection(False)
  5415. self.delete_selection_shape()
  5416. curr_sel_obj.selection_shape_drawn = False
  5417. self.collection.set_active(self.objects_under_the_click_list[0])
  5418. curr_sel_obj = self.collection.get_active()
  5419. # create the selection box around the selected object
  5420. if self.defaults['global_selection_shape'] is True:
  5421. self.draw_selection_shape(curr_sel_obj)
  5422. curr_sel_obj.selection_shape_drawn = True
  5423. self.selected_message(curr_sel_obj=curr_sel_obj)
  5424. elif curr_sel_obj.selection_shape_drawn is False:
  5425. if self.defaults['global_selection_shape'] is True:
  5426. self.draw_selection_shape(curr_sel_obj)
  5427. curr_sel_obj.selection_shape_drawn = True
  5428. else:
  5429. self.collection.on_objects_selection(False)
  5430. self.delete_selection_shape()
  5431. if self.call_source != 'app':
  5432. self.call_source = 'app'
  5433. self.selected_message(curr_sel_obj=curr_sel_obj)
  5434. else:
  5435. # If there is no selected object
  5436. # make active the first element of the overlapped objects list
  5437. if self.collection.get_active() is None:
  5438. self.collection.set_active(self.objects_under_the_click_list[0])
  5439. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5440. name_sel_obj = self.collection.get_active().options['name']
  5441. # In case that there is a selected object but it is not in the overlapped object list
  5442. # make that object inactive and activate the first element in the overlapped object list
  5443. if name_sel_obj not in self.objects_under_the_click_list:
  5444. self.collection.set_inactive(name_sel_obj)
  5445. name_sel_obj = self.objects_under_the_click_list[0]
  5446. self.collection.set_active(name_sel_obj)
  5447. else:
  5448. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5449. self.collection.set_all_inactive()
  5450. self.collection.set_active(
  5451. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5452. curr_sel_obj = self.collection.get_active()
  5453. # delete the possible selection box around a possible selected object
  5454. self.delete_selection_shape()
  5455. curr_sel_obj.selection_shape_drawn = False
  5456. # create the selection box around the selected object
  5457. if self.defaults['global_selection_shape'] is True:
  5458. self.draw_selection_shape(curr_sel_obj)
  5459. curr_sel_obj.selection_shape_drawn = True
  5460. self.selected_message(curr_sel_obj=curr_sel_obj)
  5461. else:
  5462. # deselect everything
  5463. self.collection.on_objects_selection(False)
  5464. # delete the possible selection box around a possible selected object
  5465. self.delete_selection_shape()
  5466. for o in self.collection.get_list():
  5467. o.selection_shape_drawn = False
  5468. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5469. # only when working on App
  5470. if self.call_source == 'app':
  5471. if self.click_noproject is False:
  5472. # if the Tool Tab is in focus don't change focus to Project Tab
  5473. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5474. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5475. else:
  5476. # restore auto open the Project Tab
  5477. self.click_noproject = False
  5478. # delete any text in the status bar, implicitly the last object name that was selected
  5479. # self.inform.emit("")
  5480. else:
  5481. self.call_source = 'app'
  5482. except Exception as e:
  5483. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5484. def selected_message(self, curr_sel_obj):
  5485. if curr_sel_obj:
  5486. if curr_sel_obj.kind == 'gerber':
  5487. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5488. color='green',
  5489. name=str(curr_sel_obj.options['name']),
  5490. tx=_("selected"))
  5491. )
  5492. elif curr_sel_obj.kind == 'excellon':
  5493. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5494. color='brown',
  5495. name=str(curr_sel_obj.options['name']),
  5496. tx=_("selected"))
  5497. )
  5498. elif curr_sel_obj.kind == 'cncjob':
  5499. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5500. color='blue',
  5501. name=str(curr_sel_obj.options['name']),
  5502. tx=_("selected"))
  5503. )
  5504. elif curr_sel_obj.kind == 'geometry':
  5505. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5506. color='red',
  5507. name=str(curr_sel_obj.options['name']),
  5508. tx=_("selected"))
  5509. )
  5510. def delete_hover_shape(self):
  5511. self.hover_shapes.clear()
  5512. self.hover_shapes.redraw()
  5513. def draw_hover_shape(self, sel_obj, color=None):
  5514. """
  5515. :param sel_obj: The object for which the hover shape must be drawn
  5516. :param color: The color of the hover shape
  5517. :return: None
  5518. """
  5519. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5520. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5521. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5522. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5523. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5524. if self.defaults['units'].upper() == 'MM':
  5525. hover_rect = hover_rect.buffer(-0.1)
  5526. hover_rect = hover_rect.buffer(0.2)
  5527. else:
  5528. hover_rect = hover_rect.buffer(-0.00393)
  5529. hover_rect = hover_rect.buffer(0.00787)
  5530. # if color:
  5531. # face = Color(color)
  5532. # face.alpha = 0.2
  5533. # outline = Color(color, alpha=0.8)
  5534. # else:
  5535. # face = Color(self.defaults['global_sel_fill'])
  5536. # face.alpha = 0.2
  5537. # outline = self.defaults['global_sel_line']
  5538. if color:
  5539. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5540. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5541. else:
  5542. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5543. outline = self.defaults['global_sel_line']
  5544. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5545. if self.is_legacy is True:
  5546. self.hover_shapes.redraw()
  5547. def delete_selection_shape(self):
  5548. self.move_tool.sel_shapes.clear()
  5549. self.move_tool.sel_shapes.redraw()
  5550. def draw_selection_shape(self, sel_obj, color=None):
  5551. """
  5552. Will draw a selection shape around the selected object.
  5553. :param sel_obj: The object for which the selection shape must be drawn
  5554. :param color: The color for the selection shape.
  5555. :return: None
  5556. """
  5557. if sel_obj is None:
  5558. return
  5559. # it's a line without area
  5560. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5561. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5562. # it's a geometry with area
  5563. else:
  5564. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5565. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5566. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5567. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5568. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5569. b_sel_rect = None
  5570. try:
  5571. if self.defaults['units'].upper() == 'MM':
  5572. b_sel_rect = sel_rect.buffer(-0.1)
  5573. b_sel_rect = b_sel_rect.buffer(0.2)
  5574. else:
  5575. b_sel_rect = sel_rect.buffer(-0.00393)
  5576. b_sel_rect = b_sel_rect.buffer(0.00787)
  5577. except Exception:
  5578. pass
  5579. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5580. b_sel_rect = sel_rect
  5581. if color:
  5582. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5583. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5584. else:
  5585. if self.is_legacy is False:
  5586. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5587. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5588. else:
  5589. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5590. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5591. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5592. color=outline,
  5593. face_color=face,
  5594. update=True,
  5595. layer=0,
  5596. tolerance=None))
  5597. if self.is_legacy is True:
  5598. self.move_tool.sel_shapes.redraw()
  5599. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5600. """
  5601. Will draw a selection shape when dragging mouse on canvas.
  5602. :param old_coords: Old coordinates
  5603. :param coords: New coordinates
  5604. :param kwargs: Keyword arguments
  5605. :return:
  5606. """
  5607. if 'color' in kwargs:
  5608. color = kwargs['color']
  5609. else:
  5610. color = self.defaults['global_sel_line']
  5611. if 'face_color' in kwargs:
  5612. face_color = kwargs['face_color']
  5613. else:
  5614. face_color = self.defaults['global_sel_fill']
  5615. if 'face_alpha' in kwargs:
  5616. face_alpha = kwargs['face_alpha']
  5617. else:
  5618. face_alpha = 0.3
  5619. x0, y0 = old_coords
  5620. x1, y1 = coords
  5621. pt1 = (x0, y0)
  5622. pt2 = (x1, y0)
  5623. pt3 = (x1, y1)
  5624. pt4 = (x0, y1)
  5625. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5626. # color_t = Color(face_color)
  5627. # color_t.alpha = face_alpha
  5628. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5629. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5630. layer=0, tolerance=None)
  5631. if self.is_legacy is True:
  5632. self.move_tool.sel_shapes.redraw()
  5633. def obj_properties(self):
  5634. """
  5635. Will launch the object Properties Tool
  5636. :return:
  5637. """
  5638. self.defaults.report_usage("obj_properties()")
  5639. self.properties_tool.run(toggle=False)
  5640. def on_project_context_save(self):
  5641. """
  5642. Wrapper, will save the object function of it's type
  5643. :return:
  5644. """
  5645. sel_objects = self.collection.get_selected()
  5646. len_objects = len(sel_objects)
  5647. cnt = 0
  5648. if len_objects > 1:
  5649. for o in sel_objects:
  5650. if o.kind == 'cncjob':
  5651. cnt += 1
  5652. if len_objects == cnt:
  5653. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5654. _filter_ = self.defaults['cncjob_save_filters'] + \
  5655. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5656. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5657. try:
  5658. filename, _f = FCFileSaveDialog.get_saved_filename(
  5659. caption=_("Export Code ..."),
  5660. directory=dir_file_to_save,
  5661. ext_filter=_filter_
  5662. )
  5663. except TypeError:
  5664. filename, _f = FCFileSaveDialog.get_saved_filename(
  5665. caption=_("Export Code ..."),
  5666. ext_filter=_filter_)
  5667. filename = filename.rpartition('/')[0]
  5668. for ob in sel_objects:
  5669. ob.read_form()
  5670. fname = '%s/%s' % (filename, ob.options['name'])
  5671. ob.export_gcode_handler(fname, is_gcode=True)
  5672. return
  5673. obj = self.collection.get_active()
  5674. if type(obj) == GeometryObject:
  5675. self.on_file_exportdxf()
  5676. elif type(obj) == ExcellonObject:
  5677. self.on_file_saveexcellon()
  5678. elif type(obj) == CNCJobObject:
  5679. obj.on_exportgcode_button_click()
  5680. elif type(obj) == GerberObject:
  5681. self.on_file_savegerber()
  5682. elif type(obj) == ScriptObject:
  5683. self.on_file_savescript()
  5684. elif type(obj) == DocumentObject:
  5685. self.on_file_savedocument()
  5686. def obj_move(self):
  5687. """
  5688. Callback for the Move menu entry in various Context Menu's.
  5689. :return:
  5690. """
  5691. self.defaults.report_usage("obj_move()")
  5692. self.move_tool.run(toggle=False)
  5693. # ###############################################################################################################
  5694. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5695. # ###############################################################################################################
  5696. def init_code_editor(self, name):
  5697. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5698. # add the tab if it was closed
  5699. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5700. self.text_editor_tab.setObjectName('text_editor_tab')
  5701. # delete the absolute and relative position and messages in the infobar
  5702. # self.ui.position_label.setText("")
  5703. # self.ui.rel_position_label.setText("")
  5704. # hide coordinates toolbars in the infobar while in DB
  5705. self.ui.coords_toolbar.hide()
  5706. self.ui.delta_coords_toolbar.hide()
  5707. self.toggle_codeeditor = True
  5708. self.text_editor_tab.code_editor.completer_enable = False
  5709. self.text_editor_tab.buttonRun.hide()
  5710. # make sure to keep a reference to the code editor
  5711. self.reference_code_editor = self.text_editor_tab.code_editor
  5712. # Switch plot_area to CNCJob tab
  5713. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5714. def on_view_source(self):
  5715. """
  5716. Called when the user wants to see the source file of the selected object
  5717. :return:
  5718. """
  5719. try:
  5720. obj = self.collection.get_active()
  5721. except Exception as e:
  5722. self.log.debug("App.on_view_source() --> %s" % str(e))
  5723. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5724. return 'fail'
  5725. if obj is None:
  5726. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5727. return 'fail'
  5728. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5729. self.proc_container.view.set_busy(_("Loading..."))
  5730. flt = "All Files (*.*)"
  5731. if obj.kind == 'gerber':
  5732. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5733. elif obj.kind == 'excellon':
  5734. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5735. elif obj.kind == 'cncjob':
  5736. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5737. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5738. # add the tab if it was closed
  5739. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5740. self.source_editor_tab.setObjectName('source_editor_tab')
  5741. # delete the absolute and relative position and messages in the infobar
  5742. # self.ui.position_label.setText("")
  5743. # self.ui.rel_position_label.setText("")
  5744. # hide coordinates toolbars in the infobar while in DB
  5745. self.ui.coords_toolbar.hide()
  5746. self.ui.delta_coords_toolbar.hide()
  5747. self.source_editor_tab.code_editor.completer_enable = False
  5748. self.source_editor_tab.buttonRun.hide()
  5749. # Switch plot_area to CNCJob tab
  5750. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5751. try:
  5752. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5753. except TypeError:
  5754. pass
  5755. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5756. try:
  5757. self.source_editor_tab.buttonSave.clicked.disconnect()
  5758. except TypeError:
  5759. pass
  5760. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5761. # then append the text from GCode to the text editor
  5762. if obj.kind == 'cncjob':
  5763. try:
  5764. file = obj.export_gcode(to_file=True)
  5765. if file == 'fail':
  5766. return 'fail'
  5767. except AttributeError:
  5768. self.inform.emit('[WARNING_NOTCL] %s' %
  5769. _("There is no selected object for which to see it's source file code."))
  5770. return 'fail'
  5771. else:
  5772. try:
  5773. file = StringIO(obj.source_file)
  5774. except (AttributeError, TypeError):
  5775. self.inform.emit('[WARNING_NOTCL] %s' %
  5776. _("There is no selected object for which to see it's source file code."))
  5777. return 'fail'
  5778. self.source_editor_tab.t_frame.hide()
  5779. try:
  5780. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5781. except Exception as e:
  5782. self.log.debug('App.on_view_source() -->%s' % str(e))
  5783. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5784. return
  5785. self.source_editor_tab.t_frame.show()
  5786. self.proc_container.view.set_idle()
  5787. # self.ui.show()
  5788. def on_toggle_code_editor(self):
  5789. self.defaults.report_usage("on_toggle_code_editor()")
  5790. if self.toggle_codeeditor is False:
  5791. self.init_code_editor(name=_("Code Editor"))
  5792. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5793. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5794. self.text_editor_tab.buttonSave.clicked.disconnect()
  5795. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5796. else:
  5797. for idx in range(self.ui.plot_tab_area.count()):
  5798. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5799. self.ui.plot_tab_area.closeTab(idx)
  5800. break
  5801. self.toggle_codeeditor = False
  5802. def on_code_editor_close(self):
  5803. self.toggle_codeeditor = False
  5804. def goto_text_line(self):
  5805. """
  5806. Will scroll a text to the specified text line.
  5807. :return: None
  5808. """
  5809. dia_box = Dialog_box(title=_("Go to Line ..."),
  5810. label=_("Line:"),
  5811. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5812. initial_text='')
  5813. try:
  5814. line = int(dia_box.location) - 1
  5815. except (ValueError, TypeError):
  5816. line = 0
  5817. if dia_box.ok:
  5818. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5819. # at the top of the window
  5820. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5821. # get the document() of the AppTextEditor
  5822. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5823. # create a Text Cursor based on the searched line
  5824. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5825. # set cursor of the code editor with the cursor at the searcehd line
  5826. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5827. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5828. """
  5829. Re-generates all plots from all objects.
  5830. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5831. :param muted: if True don't print messages
  5832. :param use_thread: if True will use threading for plotting the objects
  5833. :return: None
  5834. """
  5835. self.log.debug("Plot_all()")
  5836. if muted is not True:
  5837. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5838. for plot_obj in self.collection.get_list():
  5839. def worker_task(obj):
  5840. with self.proc_container.new("Plotting"):
  5841. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5842. if fit_view is True:
  5843. self.app_obj.object_plotted.emit(obj)
  5844. if use_thread is True:
  5845. # Send to worker
  5846. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5847. else:
  5848. worker_task(plot_obj)
  5849. def register_folder(self, filename):
  5850. """
  5851. Register the last folder used by the app to open something
  5852. :param filename: the last folder is extracted from the filename
  5853. :return: None
  5854. """
  5855. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5856. def register_save_folder(self, filename):
  5857. """
  5858. Register the last folder used by the app to save something
  5859. :param filename: the last folder is extracted from the filename
  5860. :return: None
  5861. """
  5862. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5863. # def set_progress_bar(self, percentage, text=""):
  5864. # """
  5865. # Set a progress bar to a value (percentage)
  5866. #
  5867. # :param percentage: Value set to the progressbar
  5868. # :param text: Not used
  5869. # :return: None
  5870. # """
  5871. # self.ui.progress_bar.setValue(int(percentage))
  5872. def setup_recent_items(self):
  5873. """
  5874. Setup a dictionary with the recent files accessed, organized by type
  5875. :return:
  5876. """
  5877. icons = {
  5878. "gerber": self.resource_location + "/flatcam_icon16.png",
  5879. "excellon": self.resource_location + "/drill16.png",
  5880. 'geometry': self.resource_location + "/geometry16.png",
  5881. "cncjob": self.resource_location + "/cnc16.png",
  5882. "script": self.resource_location + "/script_new24.png",
  5883. "document": self.resource_location + "/notes16_1.png",
  5884. "project": self.resource_location + "/project16.png",
  5885. "svg": self.resource_location + "/geometry16.png",
  5886. "dxf": self.resource_location + "/dxf16.png",
  5887. "pdf": self.resource_location + "/pdf32.png",
  5888. "image": self.resource_location + "/image16.png"
  5889. }
  5890. try:
  5891. image_opener = self.image_tool.import_image
  5892. except AttributeError:
  5893. image_opener = None
  5894. openers = {
  5895. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5896. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5897. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5898. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5899. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5900. "document": None,
  5901. 'project': self.f_handlers.open_project,
  5902. 'svg': self.f_handlers.import_svg,
  5903. 'dxf': self.f_handlers.import_dxf,
  5904. 'image': image_opener,
  5905. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5906. }
  5907. # Open recent file for files
  5908. try:
  5909. f = open(self.data_path + '/recent.json')
  5910. except IOError:
  5911. App.log.error("Failed to load recent item list.")
  5912. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5913. return
  5914. try:
  5915. self.recent = json.load(f)
  5916. except json.errors.JSONDecodeError:
  5917. App.log.error("Failed to parse recent item list.")
  5918. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5919. f.close()
  5920. return
  5921. f.close()
  5922. # Open recent file for projects
  5923. try:
  5924. fp = open(self.data_path + '/recent_projects.json')
  5925. except IOError:
  5926. App.log.error("Failed to load recent project item list.")
  5927. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5928. return
  5929. try:
  5930. self.recent_projects = json.load(fp)
  5931. except json.errors.JSONDecodeError:
  5932. App.log.error("Failed to parse recent project item list.")
  5933. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5934. fp.close()
  5935. return
  5936. fp.close()
  5937. # Closure needed to create callbacks in a loop.
  5938. # Otherwise late binding occurs.
  5939. def make_callback(func, fname):
  5940. def opener():
  5941. func(fname)
  5942. return opener
  5943. def reset_recent_files():
  5944. # Reset menu
  5945. self.ui.recent.clear()
  5946. self.recent = []
  5947. try:
  5948. ff = open(self.data_path + '/recent.json', 'w')
  5949. except IOError:
  5950. App.log.error("Failed to open recent items file for writing.")
  5951. return
  5952. json.dump(self.recent, ff)
  5953. def reset_recent_projects():
  5954. # Reset menu
  5955. self.ui.recent_projects.clear()
  5956. self.recent_projects = []
  5957. try:
  5958. frp = open(self.data_path + '/recent_projects.json', 'w')
  5959. except IOError:
  5960. App.log.error("Failed to open recent projects items file for writing.")
  5961. return
  5962. json.dump(self.recent, frp)
  5963. # Reset menu
  5964. self.ui.recent.clear()
  5965. self.ui.recent_projects.clear()
  5966. # Create menu items for projects
  5967. for recent in self.recent_projects:
  5968. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5969. if recent['kind'] == 'project':
  5970. try:
  5971. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5972. # Attach callback
  5973. o = make_callback(openers[recent["kind"]], recent['filename'])
  5974. action.triggered.connect(o)
  5975. self.ui.recent_projects.addAction(action)
  5976. except KeyError:
  5977. App.log.error("Unsupported file type: %s" % recent["kind"])
  5978. # Last action in Recent Files menu is one that Clear the content
  5979. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5980. (_("Clear Recent projects")), self)
  5981. clear_action_proj.triggered.connect(reset_recent_projects)
  5982. self.ui.recent_projects.addSeparator()
  5983. self.ui.recent_projects.addAction(clear_action_proj)
  5984. # Create menu items for files
  5985. for recent in self.recent:
  5986. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5987. if recent['kind'] != 'project':
  5988. try:
  5989. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5990. # Attach callback
  5991. o = make_callback(openers[recent["kind"]], recent['filename'])
  5992. action.triggered.connect(o)
  5993. self.ui.recent.addAction(action)
  5994. except KeyError:
  5995. App.log.error("Unsupported file type: %s" % recent["kind"])
  5996. # Last action in Recent Files menu is one that Clear the content
  5997. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5998. (_("Clear Recent files")), self)
  5999. clear_action.triggered.connect(reset_recent_files)
  6000. self.ui.recent.addSeparator()
  6001. self.ui.recent.addAction(clear_action)
  6002. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6003. # self.ui.menufilerecent.set_submenu(recent_menu)
  6004. # recent_menu.show_all()
  6005. # self.ui.recent.show()
  6006. self.log.debug("Recent items list has been populated.")
  6007. def on_properties_tab_click(self, index):
  6008. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  6009. self.setup_default_properties_tab()
  6010. def setup_default_properties_tab(self):
  6011. """
  6012. Default text for the Properties tab when is not taken by the Object UI.
  6013. :return:
  6014. """
  6015. # label = QtWidgets.QLabel("Choose an item from Project")
  6016. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6017. # sel_title = QtWidgets.QTextEdit()
  6018. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6019. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6020. #
  6021. # f_settings = QSettings("Open Source", "FlatCAM")
  6022. # if f_settings.contains("notebook_font_size"):
  6023. # fsize = f_settings.value('notebook_font_size', type=int)
  6024. # else:
  6025. # fsize = 12
  6026. #
  6027. # tsize = fsize + int(fsize / 2)
  6028. #
  6029. # selected_text = ''
  6030. #
  6031. # sel_title.setText(selected_text)
  6032. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6033. # Tree Widget
  6034. d_properties_tw = FCTree(columns=2)
  6035. d_properties_tw.setObjectName("default_properties")
  6036. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6037. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  6038. root = d_properties_tw.invisibleRootItem()
  6039. font = QtGui.QFont()
  6040. font.setBold(True)
  6041. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6042. # main Items categories
  6043. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6044. d_properties_tw.addChild(parent=general_cat,
  6045. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6046. d_properties_tw.addChild(parent=general_cat,
  6047. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6048. d_properties_tw.addChild(parent=general_cat,
  6049. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6050. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6051. d_properties_tw.addChild(parent=grid_cat,
  6052. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6053. column1=True)
  6054. d_properties_tw.addChild(parent=grid_cat,
  6055. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6056. column1=True)
  6057. d_properties_tw.addChild(parent=grid_cat,
  6058. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6059. column1=True)
  6060. d_properties_tw.addChild(parent=grid_cat,
  6061. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6062. column1=True)
  6063. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6064. d_properties_tw.addChild(parent=canvas_cat,
  6065. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6066. column1=True)
  6067. d_properties_tw.addChild(parent=canvas_cat,
  6068. title=['%s:' % _("Workspace active"),
  6069. '%s' % str(self.defaults['global_workspace'])],
  6070. column1=True)
  6071. d_properties_tw.addChild(parent=canvas_cat,
  6072. title=['%s:' % _("Workspace size"),
  6073. '%s' % str(self.defaults['global_workspaceT'])],
  6074. column1=True)
  6075. d_properties_tw.addChild(parent=canvas_cat,
  6076. title=['%s:' % _("Workspace orientation"),
  6077. '%s' % _("Portrait") if self.defaults[
  6078. 'global_workspace_orientation'] == 'p' else
  6079. _("Landscape")],
  6080. column1=True)
  6081. d_properties_tw.addChild(parent=canvas_cat,
  6082. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6083. column1=True)
  6084. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6085. def setup_obj_classes(self):
  6086. """
  6087. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6088. class.
  6089. :return: None
  6090. """
  6091. FlatCAMObj.app = self
  6092. ObjectCollection.app = self
  6093. Gerber.app = self
  6094. Excellon.app = self
  6095. Geometry.app = self
  6096. CNCjob.app = self
  6097. FCProcess.app = self
  6098. FCProcessContainer.app = self
  6099. OptionsGroupUI.app = self
  6100. def version_check(self):
  6101. """
  6102. Checks for the latest version of the program. Alerts the
  6103. user if theirs is outdated. This method is meant to be run
  6104. in a separate thread.
  6105. :return: None
  6106. """
  6107. self.log.debug("version_check()")
  6108. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6109. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6110. App.version_url,
  6111. str(self.defaults['global_serial']),
  6112. str(self.version),
  6113. str(self.os),
  6114. urllib.parse.urlencode(self.defaults["global_stats"])
  6115. )
  6116. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6117. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6118. # urllib.parse.urlencode(self.defaults["global_stats"])
  6119. else:
  6120. # no_stats dict; just so it won't break things on website
  6121. no_ststs_dict = {}
  6122. no_ststs_dict["global_ststs"] = {}
  6123. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6124. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6125. self.log.debug("Checking for updates @ %s" % full_url)
  6126. # ## Get the data
  6127. try:
  6128. f = urllib.request.urlopen(full_url)
  6129. except Exception:
  6130. # App.log.warning("Failed checking for latest version. Could not connect.")
  6131. self.log.warning("Failed checking for latest version. Could not connect.")
  6132. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6133. return
  6134. try:
  6135. data = json.load(f)
  6136. except Exception as e:
  6137. App.log.error("Could not parse information about latest version.")
  6138. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6139. self.log.debug("json.load(): %s" % str(e))
  6140. f.close()
  6141. return
  6142. f.close()
  6143. # ## Latest version?
  6144. if self.version >= data["version"]:
  6145. self.log.debug("FlatCAM is up to date!")
  6146. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6147. return
  6148. self.log.debug("Newer version available.")
  6149. self.message.emit(
  6150. _("Newer Version Available"),
  6151. '%s<br><br>><b>%s</b><br>%s' % (
  6152. _("There is a newer version of FlatCAM available for download:"),
  6153. str(data["name"]),
  6154. str(data["message"])
  6155. ),
  6156. _("info")
  6157. )
  6158. def on_plotcanvas_setup(self, container=None):
  6159. """
  6160. This is doing the setup for the plot area (canvas).
  6161. :param container: QT Widget where to install the canvas
  6162. :return: None
  6163. """
  6164. if container:
  6165. plot_container = container
  6166. else:
  6167. plot_container = self.ui.right_layout
  6168. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6169. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6170. self.is_legacy = True
  6171. self.defaults["global_graphic_engine"] = "2D"
  6172. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6173. else:
  6174. try:
  6175. self.plotcanvas = PlotCanvas(plot_container, self)
  6176. except Exception as er:
  6177. msg_txt = traceback.format_exc()
  6178. self.log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6179. self.log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6180. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6181. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6182. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6183. msg += msg_txt
  6184. self.inform.emit(msg)
  6185. return 'fail'
  6186. # So it can receive key presses
  6187. self.plotcanvas.native.setFocus()
  6188. if self.is_legacy is False:
  6189. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6190. # Set the mouse button for panning
  6191. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6192. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6193. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6194. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6195. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6196. # Keys over plot enabled
  6197. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6198. if self.defaults['global_cursor_type'] == 'small':
  6199. self.app_cursor = self.plotcanvas.new_cursor()
  6200. else:
  6201. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6202. if self.ui.grid_snap_btn.isChecked():
  6203. self.app_cursor.enabled = True
  6204. else:
  6205. self.app_cursor.enabled = False
  6206. if self.is_legacy is False:
  6207. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6208. else:
  6209. # will use the default Matplotlib axes
  6210. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6211. def on_zoom_fit(self):
  6212. """
  6213. Callback for zoom-fit request. This can be either from the corresponding
  6214. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6215. with axes limits from the geometry bounds of all objects.
  6216. :return: None
  6217. """
  6218. if self.is_legacy is False:
  6219. self.plotcanvas.fit_view()
  6220. else:
  6221. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6222. width = xmax - xmin
  6223. height = ymax - ymin
  6224. xmin -= 0.05 * width
  6225. xmax += 0.05 * width
  6226. ymin -= 0.05 * height
  6227. ymax += 0.05 * height
  6228. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6229. def on_zoom_in(self):
  6230. """
  6231. Callback for zoom-in request.
  6232. :return:
  6233. """
  6234. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6235. def on_zoom_out(self):
  6236. """
  6237. Callback for zoom-out request.
  6238. :return:
  6239. """
  6240. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6241. def disable_all_plots(self):
  6242. self.defaults.report_usage("disable_all_plots()")
  6243. self.disable_plots(self.collection.get_list())
  6244. self.inform.emit('[success] %s' % _("All plots disabled."))
  6245. def disable_other_plots(self):
  6246. self.defaults.report_usage("disable_other_plots()")
  6247. self.disable_plots(self.collection.get_non_selected())
  6248. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6249. def enable_all_plots(self):
  6250. self.defaults.report_usage("enable_all_plots()")
  6251. self.enable_plots(self.collection.get_list())
  6252. self.inform.emit('[success] %s' % _("All plots enabled."))
  6253. def enable_other_plots(self):
  6254. self.defaults.report_usage("enable_other_plots()")
  6255. self.enable_plots(self.collection.get_non_selected())
  6256. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6257. def on_enable_sel_plots(self):
  6258. self.log.debug("App.on_enable_sel_plot()")
  6259. object_list = self.collection.get_selected()
  6260. self.enable_plots(objects=object_list)
  6261. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6262. def on_disable_sel_plots(self):
  6263. self.log.debug("App.on_disable_sel_plot()")
  6264. # self.inform.emit(_("Disabling plots ..."))
  6265. object_list = self.collection.get_selected()
  6266. self.disable_plots(objects=object_list)
  6267. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6268. def enable_plots(self, objects):
  6269. """
  6270. Enable plots
  6271. :param objects: list of Objects to be enabled
  6272. :return:
  6273. """
  6274. self.log.debug("Enabling plots ...")
  6275. # self.inform.emit(_("Working ..."))
  6276. for obj in objects:
  6277. if obj.options['plot'] is False:
  6278. obj.options.set_change_callback(lambda x: None)
  6279. obj.options['plot'] = True
  6280. try:
  6281. # only the Gerber obj has on_plot_cb_click() method
  6282. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6283. # disable this cb while disconnected,
  6284. # in case the operation takes time the user is not allowed to change it
  6285. obj.ui.plot_cb.setDisabled(True)
  6286. except AttributeError:
  6287. pass
  6288. obj.set_form_item("plot")
  6289. try:
  6290. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6291. obj.ui.plot_cb.setDisabled(False)
  6292. except AttributeError:
  6293. pass
  6294. obj.options.set_change_callback(obj.on_options_change)
  6295. self.collection.update_view()
  6296. def worker_task(objs):
  6297. with self.proc_container.new(_("Enabling plots ...")):
  6298. for plot_obj in objs:
  6299. # obj.options['plot'] = True
  6300. if isinstance(plot_obj, CNCJobObject):
  6301. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6302. else:
  6303. plot_obj.plot(visible=True)
  6304. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6305. def disable_plots(self, objects):
  6306. """
  6307. Disables plots
  6308. :param objects: list of Objects to be disabled
  6309. :return:
  6310. """
  6311. self.log.debug("Disabling plots ...")
  6312. # self.inform.emit(_("Working ..."))
  6313. for obj in objects:
  6314. if obj.options['plot'] is True:
  6315. obj.options.set_change_callback(lambda x: None)
  6316. obj.options['plot'] = False
  6317. try:
  6318. # only the Gerber obj has on_plot_cb_click() method
  6319. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6320. obj.ui.plot_cb.setDisabled(True)
  6321. except AttributeError:
  6322. pass
  6323. obj.set_form_item("plot")
  6324. try:
  6325. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6326. obj.ui.plot_cb.setDisabled(False)
  6327. except AttributeError:
  6328. pass
  6329. obj.options.set_change_callback(obj.on_options_change)
  6330. try:
  6331. self.delete_selection_shape()
  6332. except Exception as e:
  6333. self.log.debug("App.disable_plots() --> %s" % str(e))
  6334. self.collection.update_view()
  6335. def worker_task(objs):
  6336. with self.proc_container.new(_("Disabling plots ...")):
  6337. for plot_obj in objs:
  6338. # obj.options['plot'] = True
  6339. if isinstance(plot_obj, CNCJobObject):
  6340. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6341. else:
  6342. plot_obj.plot(visible=False)
  6343. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6344. def toggle_plots(self, objects):
  6345. """
  6346. Toggle plots visibility
  6347. :param objects: list of Objects for which to be toggled the visibility
  6348. :return: None
  6349. """
  6350. # if no objects selected then do nothing
  6351. if not self.collection.get_selected():
  6352. return
  6353. self.log.debug("Toggling plots ...")
  6354. self.inform.emit(_("Working ..."))
  6355. for obj in objects:
  6356. if obj.options['plot'] is False:
  6357. obj.options['plot'] = True
  6358. else:
  6359. obj.options['plot'] = False
  6360. self.app_obj.plots_updated.emit()
  6361. def clear_plots(self):
  6362. """
  6363. Clear the plots
  6364. :return: None
  6365. """
  6366. objects = self.collection.get_list()
  6367. for obj in objects:
  6368. obj.clear(obj == objects[-1])
  6369. # Clear pool to free memory
  6370. self.clear_pool()
  6371. def on_set_color_action_triggered(self):
  6372. """
  6373. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6374. :return:
  6375. """
  6376. new_color = self.defaults['gerber_plot_fill']
  6377. clicked_action = self.sender()
  6378. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6379. act_name = clicked_action.text()
  6380. sel_obj_list = self.collection.get_selected()
  6381. if not sel_obj_list:
  6382. return
  6383. # a default value, I just chose this one
  6384. alpha_level = 'BF'
  6385. for sel_obj in sel_obj_list:
  6386. if sel_obj.kind == 'excellon':
  6387. alpha_level = str(hex(
  6388. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6389. elif sel_obj.kind == 'gerber':
  6390. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6391. elif sel_obj.kind == 'geometry':
  6392. alpha_level = 'FF'
  6393. else:
  6394. self.log.debug(
  6395. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6396. continue
  6397. sel_obj.alpha_level = alpha_level
  6398. if act_name == _('Red'):
  6399. new_color = '#FF0000' + alpha_level
  6400. if act_name == _('Blue'):
  6401. new_color = '#0000FF' + alpha_level
  6402. if act_name == _('Yellow'):
  6403. new_color = '#FFDF00' + alpha_level
  6404. if act_name == _('Green'):
  6405. new_color = '#00FF00' + alpha_level
  6406. if act_name == _('Purple'):
  6407. new_color = '#FF00FF' + alpha_level
  6408. if act_name == _('Brown'):
  6409. new_color = '#A52A2A' + alpha_level
  6410. if act_name == _('White'):
  6411. new_color = '#FFFFFF' + alpha_level
  6412. if act_name == _('Black'):
  6413. new_color = '#000000' + alpha_level
  6414. if act_name == _('Custom'):
  6415. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6416. c_dialog = QtWidgets.QColorDialog()
  6417. plot_fill_color = c_dialog.getColor(initial=new_color)
  6418. if plot_fill_color.isValid() is False:
  6419. return
  6420. new_color = str(plot_fill_color.name()) + alpha_level
  6421. if act_name == _("Default"):
  6422. for sel_obj in sel_obj_list:
  6423. if sel_obj.kind == 'excellon':
  6424. new_color = self.defaults['excellon_plot_fill']
  6425. new_line_color = self.defaults['excellon_plot_line']
  6426. elif sel_obj.kind == 'gerber':
  6427. new_color = self.defaults['gerber_plot_fill']
  6428. new_line_color = self.defaults['gerber_plot_line']
  6429. elif sel_obj.kind == 'geometry':
  6430. new_color = self.defaults['geometry_plot_line']
  6431. new_line_color = self.defaults['geometry_plot_line']
  6432. else:
  6433. self.log.debug(
  6434. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6435. continue
  6436. sel_obj.fill_color = new_color
  6437. sel_obj.outline_color = new_line_color
  6438. sel_obj.shapes.redraw(
  6439. update_colors=(new_color, new_line_color)
  6440. )
  6441. return
  6442. if act_name == _("Opacity"):
  6443. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6444. # '%s:' % _("Value"),
  6445. # min=0, max=255, step=1, value=191)
  6446. alpha_dialog = FCInputDialogSlider(
  6447. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6448. alpha_level, ok_button = alpha_dialog.get_results()
  6449. if ok_button:
  6450. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6451. for sel_obj in sel_obj_list:
  6452. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6453. sel_obj.shapes.redraw(
  6454. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6455. )
  6456. return
  6457. new_line_color = color_variant(new_color[:7], 0.7)
  6458. if act_name == _("White"):
  6459. new_line_color = color_variant("#dedede", 0.7)
  6460. for sel_obj in sel_obj_list:
  6461. sel_obj.fill_color = new_color
  6462. sel_obj.outline_color = new_line_color
  6463. sel_obj.shapes.redraw(
  6464. update_colors=(new_color, new_line_color)
  6465. )
  6466. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6467. group = self.collection.group_items["gerber"]
  6468. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6469. new_c = (new_line_color, new_color)
  6470. for sel_obj in sel_obj_list:
  6471. if sel_obj.kind == 'gerber':
  6472. item = sel_obj.item
  6473. item_index = self.collection.index(item.row(), 0, group_index)
  6474. idx = item_index.row()
  6475. self.defaults["gerber_color_list"][idx] = new_c
  6476. def generate_cnc_job(self, objects):
  6477. """
  6478. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6479. :param objects: Selected objects in the Project Tab
  6480. :return:
  6481. """
  6482. self.defaults.report_usage("generate_cnc_job()")
  6483. # for obj in objects:
  6484. # obj.generatecncjob()
  6485. for obj in objects:
  6486. obj.on_generatecnc_button_click()
  6487. def start_delayed_quit(self, delay, filename, should_quit=None):
  6488. """
  6489. :param delay: period of checking if project file size is more than zero; in seconds
  6490. :param filename: the name of the project file to be checked periodically for size more than zero
  6491. :param should_quit: if the task finished will be followed by an app quit; boolean
  6492. :return:
  6493. """
  6494. to_quit = should_quit
  6495. self.save_timer = QtCore.QTimer()
  6496. self.save_timer.setInterval(delay)
  6497. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6498. self.save_timer.start()
  6499. def check_project_file_size(self, filename, should_quit=None):
  6500. """
  6501. :param filename: the name of the project file to be checked periodically for size more than zero
  6502. :param should_quit: will quit the app if True; boolean
  6503. :return:
  6504. """
  6505. try:
  6506. if os.stat(filename).st_size > 0:
  6507. self.save_in_progress = False
  6508. self.save_timer.stop()
  6509. if should_quit:
  6510. self.app_quit.emit()
  6511. except Exception:
  6512. traceback.print_exc()
  6513. def save_project_auto(self):
  6514. """
  6515. Called periodically to save the project.
  6516. 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
  6517. # progress.
  6518. :return:
  6519. """
  6520. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6521. self.on_file_saveproject()
  6522. def save_project_auto_update(self):
  6523. """
  6524. Update the auto save time interval value.
  6525. :return:
  6526. """
  6527. self.log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6528. try:
  6529. if self.autosave_timer.isActive():
  6530. self.autosave_timer.stop()
  6531. except Exception:
  6532. pass
  6533. if self.defaults['global_autosave'] is True:
  6534. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6535. self.autosave_timer.start()
  6536. def on_options_app2project(self):
  6537. """
  6538. Callback for Options->Transfer Options->App=>Project. Copies options
  6539. from application defaults to project defaults.
  6540. :return: None
  6541. """
  6542. self.defaults.report_usage("on_options_app2project")
  6543. self.preferencesUiManager.defaults_read_form()
  6544. self.options.update(self.defaults)
  6545. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6546. """
  6547. Shows a message on the FlatCAM Shell
  6548. :param msg: Message to display.
  6549. :param show: Opens the shell.
  6550. :param error: Shows the message as an error.
  6551. :param warning: Shows the message as an warning.
  6552. :param success: Shows the message as an success.
  6553. :param selected: Indicate that something was selected on canvas
  6554. :return: None
  6555. """
  6556. end = '\n' if new_line is True else ''
  6557. if show:
  6558. self.ui.shell_dock.show()
  6559. try:
  6560. if error:
  6561. self.shell.append_error(msg + end)
  6562. elif warning:
  6563. self.shell.append_warning(msg + end)
  6564. elif success:
  6565. self.shell.append_success(msg + end)
  6566. elif selected:
  6567. self.shell.append_selected(msg + end)
  6568. else:
  6569. self.shell.append_output(msg + end)
  6570. except AttributeError:
  6571. self.log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6572. def dec_format(self, val, dec=None):
  6573. """
  6574. Returns a formatted float value with a certain number of decimals
  6575. """
  6576. dec_nr = dec if dec is not None else self.decimals
  6577. return float('%.*f' % (dec_nr, val))
  6578. class ArgsThread(QtCore.QObject):
  6579. open_signal = pyqtSignal(list)
  6580. start = pyqtSignal()
  6581. stop = pyqtSignal()
  6582. if sys.platform == 'win32':
  6583. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6584. else:
  6585. address = ('/tmp/testipc', 'AF_UNIX')
  6586. def __init__(self):
  6587. super().__init__()
  6588. self.listener = None
  6589. self.thread_exit = False
  6590. self.start.connect(self.run)
  6591. self.stop.connect(self.close_listener)
  6592. def my_loop(self, address):
  6593. try:
  6594. self.listener = Listener(*address)
  6595. while self.thread_exit is False:
  6596. conn = self.listener.accept()
  6597. self.serve(conn)
  6598. except socket.error:
  6599. try:
  6600. conn = Client(*address)
  6601. conn.send(sys.argv)
  6602. conn.send('close')
  6603. # close the current instance only if there are args
  6604. if len(sys.argv) > 1:
  6605. try:
  6606. self.listener.close()
  6607. except Exception:
  6608. pass
  6609. sys.exit()
  6610. except ConnectionRefusedError:
  6611. if sys.platform == 'win32':
  6612. pass
  6613. else:
  6614. os.system('rm /tmp/testipc')
  6615. self.listener = Listener(*address)
  6616. while True:
  6617. conn = self.listener.accept()
  6618. self.serve(conn)
  6619. def serve(self, conn):
  6620. while self.thread_exit is False:
  6621. msg = conn.recv()
  6622. if msg == 'close':
  6623. break
  6624. self.open_signal.emit(msg)
  6625. conn.close()
  6626. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6627. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6628. @pyqtSlot()
  6629. def run(self):
  6630. self.my_loop(self.address)
  6631. @pyqtSlot()
  6632. def close_listener(self):
  6633. self.thread_exit = True
  6634. self.listener.close()
  6635. class MenuFileHandlers(QtCore.QObject):
  6636. def __init__(self, app):
  6637. super().__init__()
  6638. self.app = app
  6639. self.inform = self.app.inform
  6640. self.splash = self.app.splash
  6641. self.worker_task = self.app.worker_task
  6642. self.defaults = self.app.defaults
  6643. self.pagesize = {}
  6644. def on_fileopengerber(self, signal, name=None):
  6645. """
  6646. File menu callback for opening a Gerber.
  6647. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6648. :param name:
  6649. :return: None
  6650. """
  6651. self.app.log.debug("on_fileopengerber()")
  6652. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6653. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6654. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6655. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6656. "*.outline);;" \
  6657. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6658. "*.mil);;" \
  6659. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6660. "Allegro Files (*.art);;" \
  6661. "Mentor Files (*.pho *.gdo);;" \
  6662. "All Files (*.*)"
  6663. if name is None:
  6664. try:
  6665. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6666. directory=self.app.get_last_folder(),
  6667. filter=_filter_,
  6668. initialFilter=self.app.last_op_gerber_filter)
  6669. except TypeError:
  6670. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6671. filenames = [str(filename) for filename in filenames]
  6672. self.app.last_op_gerber_filter = _f
  6673. else:
  6674. filenames = [name]
  6675. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6676. "Canvas initialization finished in"),
  6677. '%.2f' % self.app.used_time,
  6678. _("Opening Gerber file.")),
  6679. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6680. color=QtGui.QColor("gray"))
  6681. if len(filenames) == 0:
  6682. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6683. else:
  6684. for filename in filenames:
  6685. if filename != '':
  6686. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6687. def on_fileopenexcellon(self, signal, name=None):
  6688. """
  6689. File menu callback for opening an Excellon file.
  6690. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6691. :param name:
  6692. :return: None
  6693. """
  6694. self.app.log.debug("on_fileopenexcellon()")
  6695. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6696. "All Files (*.*)"
  6697. if name is None:
  6698. try:
  6699. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6700. directory=self.app.get_last_folder(),
  6701. filter=_filter_,
  6702. initialFilter=self.app.last_op_excellon_filter)
  6703. except TypeError:
  6704. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6705. filenames = [str(filename) for filename in filenames]
  6706. self.app.last_op_excellon_filter = _f
  6707. else:
  6708. filenames = [str(name)]
  6709. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6710. "Canvas initialization finished in"),
  6711. '%.2f' % self.app.used_time,
  6712. _("Opening Excellon file.")),
  6713. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6714. color=QtGui.QColor("gray"))
  6715. if len(filenames) == 0:
  6716. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6717. else:
  6718. for filename in filenames:
  6719. if filename != '':
  6720. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6721. def on_fileopengcode(self, signal, name=None):
  6722. """
  6723. File menu call back for opening gcode.
  6724. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6725. :param name:
  6726. :return:
  6727. """
  6728. self.app.log.debug("on_fileopengcode()")
  6729. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6730. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6731. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6732. "All Files (*.*)"
  6733. if name is None:
  6734. try:
  6735. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6736. directory=self.app.get_last_folder(),
  6737. filter=_filter_,
  6738. initialFilter=self.app.last_op_gcode_filter)
  6739. except TypeError:
  6740. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6741. filenames = [str(filename) for filename in filenames]
  6742. self.app.last_op_gcode_filter = _f
  6743. else:
  6744. filenames = [name]
  6745. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6746. "Canvas initialization finished in"),
  6747. '%.2f' % self.app.used_time,
  6748. _("Opening G-Code file.")),
  6749. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6750. color=QtGui.QColor("gray"))
  6751. if len(filenames) == 0:
  6752. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6753. else:
  6754. for filename in filenames:
  6755. if filename != '':
  6756. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6757. def on_file_openproject(self, signal):
  6758. """
  6759. File menu callback for opening a project.
  6760. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6761. :return: None
  6762. """
  6763. self.app.log.debug("on_file_openproject()")
  6764. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6765. try:
  6766. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6767. directory=self.app.get_last_folder(), filter=_filter_)
  6768. except TypeError:
  6769. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6770. filename = str(filename)
  6771. if filename == "":
  6772. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6773. else:
  6774. # self.worker_task.emit({'fcn': self.open_project,
  6775. # 'params': [filename]})
  6776. # The above was failing because open_project() is not
  6777. # thread safe. The new_project()
  6778. self.open_project(filename)
  6779. def on_fileopenhpgl2(self, signal, name=None):
  6780. """
  6781. File menu callback for opening a HPGL2.
  6782. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6783. :param name:
  6784. :return: None
  6785. """
  6786. self.app.log.debug("on_fileopenhpgl2()")
  6787. _filter_ = "HPGL2 Files (*.plt);;" \
  6788. "All Files (*.*)"
  6789. if name is None:
  6790. try:
  6791. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6792. directory=self.app.get_last_folder(),
  6793. filter=_filter_)
  6794. except TypeError:
  6795. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6796. filenames = [str(filename) for filename in filenames]
  6797. else:
  6798. filenames = [name]
  6799. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6800. "Canvas initialization finished in"),
  6801. '%.2f' % self.app.used_time,
  6802. _("Opening HPGL2 file.")),
  6803. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6804. color=QtGui.QColor("gray"))
  6805. if len(filenames) == 0:
  6806. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6807. else:
  6808. for filename in filenames:
  6809. if filename != '':
  6810. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6811. def on_file_openconfig(self, signal):
  6812. """
  6813. File menu callback for opening a config file.
  6814. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6815. :return: None
  6816. """
  6817. self.app.log.debug("on_file_openconfig()")
  6818. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6819. try:
  6820. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6821. directory=self.app.data_path, filter=_filter_)
  6822. except TypeError:
  6823. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6824. filter=_filter_)
  6825. if filename == "":
  6826. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6827. else:
  6828. self.open_config_file(filename)
  6829. def on_file_exportsvg(self):
  6830. """
  6831. Callback for menu item File->Export SVG.
  6832. :return: None
  6833. """
  6834. self.app.log.debug("on_file_exportsvg()")
  6835. obj = self.app.collection.get_active()
  6836. if obj is None:
  6837. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6838. msg = _("Please Select a Geometry object to export")
  6839. msgbox = QtWidgets.QMessageBox()
  6840. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6841. msgbox.setInformativeText(msg)
  6842. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6843. msgbox.setDefaultButton(bt_ok)
  6844. msgbox.exec_()
  6845. return
  6846. # Check for more compatible types and add as required
  6847. if (not isinstance(obj, GeometryObject)
  6848. and not isinstance(obj, GerberObject)
  6849. and not isinstance(obj, CNCJobObject)
  6850. and not isinstance(obj, ExcellonObject)):
  6851. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6852. msgbox = QtWidgets.QMessageBox()
  6853. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6854. msgbox.setInformativeText(msg)
  6855. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6856. msgbox.setDefaultButton(bt_ok)
  6857. msgbox.exec_()
  6858. return
  6859. name = obj.options["name"]
  6860. _filter = "SVG File (*.svg);;All Files (*.*)"
  6861. try:
  6862. filename, _f = FCFileSaveDialog.get_saved_filename(
  6863. caption=_("Export SVG"),
  6864. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6865. ext_filter=_filter)
  6866. except TypeError:
  6867. filename, _f = FCFileSaveDialog.get_saved_filename(
  6868. caption=_("Export SVG"),
  6869. ext_filter=_filter)
  6870. filename = str(filename)
  6871. if filename == "":
  6872. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6873. return
  6874. else:
  6875. self.export_svg(name, filename)
  6876. if self.defaults["global_open_style"] is False:
  6877. self.app.file_opened.emit("SVG", filename)
  6878. self.app.file_saved.emit("SVG", filename)
  6879. def on_file_exportpng(self):
  6880. self.app.log.debug("on_file_exportpng()")
  6881. date = str(datetime.today()).rpartition('.')[0]
  6882. date = ''.join(c for c in date if c not in ':-')
  6883. date = date.replace(' ', '_')
  6884. data = None
  6885. if self.app.is_legacy is False:
  6886. image = _screenshot(alpha=False)
  6887. data = np.asarray(image)
  6888. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6889. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6890. return
  6891. filter_ = "PNG File (*.png);;All Files (*.*)"
  6892. try:
  6893. filename, _f = FCFileSaveDialog.get_saved_filename(
  6894. caption=_("Export PNG Image"),
  6895. directory=self.app.get_last_save_folder() + '/png_' + date,
  6896. ext_filter=filter_)
  6897. except TypeError:
  6898. filename, _f = FCFileSaveDialog.get_saved_filename(
  6899. caption=_("Export PNG Image"),
  6900. ext_filter=filter_)
  6901. filename = str(filename)
  6902. if filename == "":
  6903. self.inform.emit(_("Cancelled."))
  6904. return
  6905. else:
  6906. if self.app.is_legacy is False:
  6907. write_png(filename, data)
  6908. else:
  6909. self.app.plotcanvas.figure.savefig(filename)
  6910. if self.defaults["global_open_style"] is False:
  6911. self.app.file_opened.emit("png", filename)
  6912. self.app.file_saved.emit("png", filename)
  6913. def on_file_savegerber(self):
  6914. """
  6915. Callback for menu item in Project context menu.
  6916. :return: None
  6917. """
  6918. self.app.log.debug("on_file_savegerber()")
  6919. obj = self.app.collection.get_active()
  6920. if obj is None:
  6921. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6922. return
  6923. # Check for more compatible types and add as required
  6924. if not isinstance(obj, GerberObject):
  6925. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6926. return
  6927. name = self.app.collection.get_active().options["name"]
  6928. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6929. try:
  6930. filename, _f = FCFileSaveDialog.get_saved_filename(
  6931. caption="Save Gerber source file",
  6932. directory=self.app.get_last_save_folder() + '/' + name,
  6933. ext_filter=_filter)
  6934. except TypeError:
  6935. filename, _f = FCFileSaveDialog.get_saved_filename(
  6936. caption=_("Save Gerber source file"),
  6937. ext_filter=_filter)
  6938. filename = str(filename)
  6939. if filename == "":
  6940. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6941. return
  6942. else:
  6943. self.save_source_file(name, filename)
  6944. if self.defaults["global_open_style"] is False:
  6945. self.app.file_opened.emit("Gerber", filename)
  6946. self.app.file_saved.emit("Gerber", filename)
  6947. def on_file_savescript(self):
  6948. """
  6949. Callback for menu item in Project context menu.
  6950. :return: None
  6951. """
  6952. self.app.log.debug("on_file_savescript()")
  6953. obj = self.app.collection.get_active()
  6954. if obj is None:
  6955. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6956. return
  6957. # Check for more compatible types and add as required
  6958. if not isinstance(obj, ScriptObject):
  6959. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6960. return
  6961. name = self.app.collection.get_active().options["name"]
  6962. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6963. try:
  6964. filename, _f = FCFileSaveDialog.get_saved_filename(
  6965. caption="Save Script source file",
  6966. directory=self.app.get_last_save_folder() + '/' + name,
  6967. ext_filter=_filter)
  6968. except TypeError:
  6969. filename, _f = FCFileSaveDialog.get_saved_filename(
  6970. caption=_("Save Script source file"),
  6971. ext_filter=_filter)
  6972. filename = str(filename)
  6973. if filename == "":
  6974. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6975. return
  6976. else:
  6977. self.save_source_file(name, filename)
  6978. if self.defaults["global_open_style"] is False:
  6979. self.app.file_opened.emit("Script", filename)
  6980. self.app.file_saved.emit("Script", filename)
  6981. def on_file_savedocument(self):
  6982. """
  6983. Callback for menu item in Project context menu.
  6984. :return: None
  6985. """
  6986. self.app.log.debug("on_file_savedocument()")
  6987. obj = self.app.collection.get_active()
  6988. if obj is None:
  6989. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6990. return
  6991. # Check for more compatible types and add as required
  6992. if not isinstance(obj, ScriptObject):
  6993. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6994. return
  6995. name = self.app.collection.get_active().options["name"]
  6996. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6997. try:
  6998. filename, _f = FCFileSaveDialog.get_saved_filename(
  6999. caption="Save Document source file",
  7000. directory=self.app.get_last_save_folder() + '/' + name,
  7001. ext_filter=_filter)
  7002. except TypeError:
  7003. filename, _f = FCFileSaveDialog.get_saved_filename(
  7004. caption=_("Save Document source file"),
  7005. ext_filter=_filter)
  7006. filename = str(filename)
  7007. if filename == "":
  7008. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7009. return
  7010. else:
  7011. self.save_source_file(name, filename)
  7012. if self.defaults["global_open_style"] is False:
  7013. self.app.file_opened.emit("Document", filename)
  7014. self.app.file_saved.emit("Document", filename)
  7015. def on_file_saveexcellon(self):
  7016. """
  7017. Callback for menu item in project context menu.
  7018. :return: None
  7019. """
  7020. self.app.log.debug("on_file_saveexcellon()")
  7021. obj = self.app.collection.get_active()
  7022. if obj is None:
  7023. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7024. return
  7025. # Check for more compatible types and add as required
  7026. if not isinstance(obj, ExcellonObject):
  7027. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7028. return
  7029. name = self.app.collection.get_active().options["name"]
  7030. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7031. try:
  7032. filename, _f = FCFileSaveDialog.get_saved_filename(
  7033. caption=_("Save Excellon source file"),
  7034. directory=self.app.get_last_save_folder() + '/' + name,
  7035. ext_filter=_filter)
  7036. except TypeError:
  7037. filename, _f = FCFileSaveDialog.get_saved_filename(
  7038. caption=_("Save Excellon source file"), ext_filter=_filter)
  7039. filename = str(filename)
  7040. if filename == "":
  7041. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7042. return
  7043. else:
  7044. self.save_source_file(name, filename)
  7045. if self.defaults["global_open_style"] is False:
  7046. self.app.file_opened.emit("Excellon", filename)
  7047. self.app.file_saved.emit("Excellon", filename)
  7048. def on_file_exportexcellon(self):
  7049. """
  7050. Callback for menu item File->Export->Excellon.
  7051. :return: None
  7052. """
  7053. self.app.log.debug("on_file_exportexcellon()")
  7054. obj = self.app.collection.get_active()
  7055. if obj is None:
  7056. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7057. return
  7058. # Check for more compatible types and add as required
  7059. if not isinstance(obj, ExcellonObject):
  7060. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7061. return
  7062. name = self.app.collection.get_active().options["name"]
  7063. _filter = self.defaults["excellon_save_filters"]
  7064. try:
  7065. filename, _f = FCFileSaveDialog.get_saved_filename(
  7066. caption=_("Export Excellon"),
  7067. directory=self.app.get_last_save_folder() + '/' + name,
  7068. ext_filter=_filter)
  7069. except TypeError:
  7070. filename, _f = FCFileSaveDialog.get_saved_filename(
  7071. caption=_("Export Excellon"),
  7072. ext_filter=_filter)
  7073. filename = str(filename)
  7074. if filename == "":
  7075. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7076. return
  7077. else:
  7078. used_extension = filename.rpartition('.')[2]
  7079. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7080. self.export_excellon(name, filename)
  7081. if self.defaults["global_open_style"] is False:
  7082. self.app.file_opened.emit("Excellon", filename)
  7083. self.app.file_saved.emit("Excellon", filename)
  7084. def on_file_exportgerber(self):
  7085. """
  7086. Callback for menu item File->Export->Gerber.
  7087. :return: None
  7088. """
  7089. App.log.debug("on_file_exportgerber()")
  7090. obj = self.app.collection.get_active()
  7091. if obj is None:
  7092. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7093. return
  7094. # Check for more compatible types and add as required
  7095. if not isinstance(obj, GerberObject):
  7096. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7097. return
  7098. name = self.app.collection.get_active().options["name"]
  7099. _filter_ = self.defaults['gerber_save_filters']
  7100. try:
  7101. filename, _f = FCFileSaveDialog.get_saved_filename(
  7102. caption=_("Export Gerber"),
  7103. directory=self.app.get_last_save_folder() + '/' + name,
  7104. ext_filter=_filter_)
  7105. except TypeError:
  7106. filename, _f = FCFileSaveDialog.get_saved_filename(
  7107. caption=_("Export Gerber"),
  7108. ext_filter=_filter_)
  7109. filename = str(filename)
  7110. if filename == "":
  7111. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7112. return
  7113. else:
  7114. used_extension = filename.rpartition('.')[2]
  7115. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7116. self.export_gerber(name, filename)
  7117. if self.defaults["global_open_style"] is False:
  7118. self.app.file_opened.emit("Gerber", filename)
  7119. self.app.file_saved.emit("Gerber", filename)
  7120. def on_file_exportdxf(self):
  7121. """
  7122. Callback for menu item File->Export DXF.
  7123. :return: None
  7124. """
  7125. App.log.debug("on_file_exportdxf()")
  7126. obj = self.app.collection.get_active()
  7127. if obj is None:
  7128. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7129. msg = _("Please Select a Geometry object to export")
  7130. msgbox = QtWidgets.QMessageBox()
  7131. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7132. msgbox.setInformativeText(msg)
  7133. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7134. msgbox.setDefaultButton(bt_ok)
  7135. msgbox.exec_()
  7136. return
  7137. # Check for more compatible types and add as required
  7138. if not isinstance(obj, GeometryObject):
  7139. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7140. msgbox = QtWidgets.QMessageBox()
  7141. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7142. msgbox.setInformativeText(msg)
  7143. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7144. msgbox.setDefaultButton(bt_ok)
  7145. msgbox.exec_()
  7146. return
  7147. name = self.app.collection.get_active().options["name"]
  7148. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7149. try:
  7150. filename, _f = FCFileSaveDialog.get_saved_filename(
  7151. caption=_("Export DXF"),
  7152. directory=self.app.get_last_save_folder() + '/' + name,
  7153. ext_filter=_filter_)
  7154. except TypeError:
  7155. filename, _f = FCFileSaveDialog.get_saved_filename(
  7156. caption=_("Export DXF"),
  7157. ext_filter=_filter_)
  7158. filename = str(filename)
  7159. if filename == "":
  7160. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7161. return
  7162. else:
  7163. self.export_dxf(name, filename)
  7164. if self.defaults["global_open_style"] is False:
  7165. self.app.file_opened.emit("DXF", filename)
  7166. self.app.file_saved.emit("DXF", filename)
  7167. def on_file_importsvg(self, type_of_obj):
  7168. """
  7169. Callback for menu item File->Import SVG.
  7170. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7171. :type type_of_obj: str
  7172. :return: None
  7173. """
  7174. self.app.log.debug("on_file_importsvg()")
  7175. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7176. try:
  7177. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7178. directory=self.app.get_last_folder(),
  7179. filter=_filter_)
  7180. except TypeError:
  7181. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7182. filter=_filter_)
  7183. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7184. type_of_obj = "geometry"
  7185. filenames = [str(filename) for filename in filenames]
  7186. if len(filenames) == 0:
  7187. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7188. else:
  7189. for filename in filenames:
  7190. if filename != '':
  7191. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7192. def on_file_importdxf(self, type_of_obj):
  7193. """
  7194. Callback for menu item File->Import DXF.
  7195. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7196. :type type_of_obj: str
  7197. :return: None
  7198. """
  7199. self.app.log.debug("on_file_importdxf()")
  7200. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7201. try:
  7202. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7203. directory=self.app.get_last_folder(),
  7204. filter=_filter_)
  7205. except TypeError:
  7206. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7207. filter=_filter_)
  7208. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7209. type_of_obj = "geometry"
  7210. filenames = [str(filename) for filename in filenames]
  7211. if len(filenames) == 0:
  7212. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7213. else:
  7214. for filename in filenames:
  7215. if filename != '':
  7216. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7217. def on_file_new_click(self):
  7218. """
  7219. Callback for menu item File -> New.
  7220. Executed on clicking the Menu -> File -> New Project
  7221. :return:
  7222. """
  7223. if self.app.collection.get_list() and self.app.should_we_save:
  7224. msgbox = QtWidgets.QMessageBox()
  7225. # msgbox.setText("<B>Save changes ...</B>")
  7226. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7227. "Creating a New project will delete them.\n"
  7228. "Do you want to Save the project?"))
  7229. msgbox.setWindowTitle(_("Save changes"))
  7230. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7231. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7232. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7233. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7234. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7235. msgbox.setDefaultButton(bt_yes)
  7236. msgbox.exec_()
  7237. response = msgbox.clickedButton()
  7238. if response == bt_yes:
  7239. self.on_file_saveprojectas()
  7240. elif response == bt_cancel:
  7241. return
  7242. elif response == bt_no:
  7243. self.on_file_new()
  7244. else:
  7245. self.on_file_new()
  7246. self.inform.emit('[success] %s...' % _("New Project created"))
  7247. def on_file_new(self, cli=None):
  7248. """
  7249. Returns the application to its startup state. This method is thread-safe.
  7250. :param cli: Boolean. If True this method was run from command line
  7251. :return: None
  7252. """
  7253. self.defaults.report_usage("on_file_new")
  7254. # Remove everything from memory
  7255. self.app.log.debug("on_file_new()")
  7256. # close any editor that might be open
  7257. if self.app.call_source != 'app':
  7258. self.app.editor2object(cleanup=True)
  7259. # ## EDITOR section
  7260. self.app.geo_editor = AppGeoEditor(self.app)
  7261. self.app.exc_editor = AppExcEditor(self.app)
  7262. self.app.grb_editor = AppGerberEditor(self.app)
  7263. # Clear pool
  7264. self.app.clear_pool()
  7265. for obj in self.app.collection.get_list():
  7266. # delete shapes left drawn from mark shape_collections, if any
  7267. if isinstance(obj, GerberObject):
  7268. try:
  7269. obj.mark_shapes_storage.clear()
  7270. obj.mark_shapes.clear(update=True)
  7271. obj.mark_shapes.enabled = False
  7272. except AttributeError:
  7273. pass
  7274. # also delete annotation shapes, if any
  7275. elif isinstance(obj, CNCJobObject):
  7276. try:
  7277. obj.text_col.enabled = False
  7278. del obj.text_col
  7279. obj.annotation.clear(update=True)
  7280. del obj.annotation
  7281. except AttributeError:
  7282. pass
  7283. # delete the exclusion areas
  7284. self.app.exc_areas.clear_shapes()
  7285. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7286. self.app.shell.init_tcl()
  7287. # delete any selection shape on canvas
  7288. self.app.delete_selection_shape()
  7289. # delete all FlatCAM objects
  7290. self.app.collection.delete_all()
  7291. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7292. self.app.setup_default_properties_tab()
  7293. # Clear project filename
  7294. self.app.project_filename = None
  7295. # Load the application defaults
  7296. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7297. # Re-fresh project options
  7298. self.app.on_options_app2project()
  7299. # Init FlatCAMTools
  7300. self.app.init_tools()
  7301. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7302. if cli is None:
  7303. # we need to go in reverse because once we remove a tab then the index changes
  7304. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7305. # and so on. Therefore the deletion should be done in reverse
  7306. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7307. for index in range(wdg_count, -1, -1):
  7308. try:
  7309. self.app.ui.plot_tab_area.closeTab(index)
  7310. except Exception as e:
  7311. log.debug("App.on_file_new() --> %s" % str(e))
  7312. # # And then add again the Plot Area
  7313. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7314. self.app.ui.plot_tab_area.protectTab(0)
  7315. # take the focus of the Notebook on Project Tab.
  7316. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7317. self.app.ui.set_ui_title(name=_("New Project - Not saved"))
  7318. def on_filenewscript(self, silent=False):
  7319. """
  7320. Will create a new script file and open it in the Code Editor
  7321. :param silent: if True will not display status messages
  7322. :return: None
  7323. """
  7324. if silent is False:
  7325. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7326. # hide coordinates toolbars in the infobar while in DB
  7327. self.app.ui.coords_toolbar.hide()
  7328. self.app.ui.delta_coords_toolbar.hide()
  7329. self.app.app_obj.new_script_object()
  7330. def on_fileopenscript(self, name=None, silent=False):
  7331. """
  7332. Will open a Tcl script file into the Code Editor
  7333. :param silent: if True will not display status messages
  7334. :param name: name of a Tcl script file to open
  7335. :return: None
  7336. """
  7337. self.app.log.debug("on_fileopenscript()")
  7338. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7339. "All Files (*.*)"
  7340. if name:
  7341. filenames = [name]
  7342. else:
  7343. try:
  7344. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7345. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7346. except TypeError:
  7347. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7348. if len(filenames) == 0:
  7349. if silent is False:
  7350. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7351. else:
  7352. for filename in filenames:
  7353. if filename != '':
  7354. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7355. def on_fileopenscript_example(self, name=None, silent=False):
  7356. """
  7357. Will open a Tcl script file into the Code Editor
  7358. :param silent: if True will not display status messages
  7359. :param name: name of a Tcl script file to open
  7360. :return:
  7361. """
  7362. self.app.log.debug("on_fileopenscript_example()")
  7363. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7364. "All Files (*.*)"
  7365. # test if the app was frozen and choose the path for the configuration file
  7366. if getattr(sys, "frozen", False) is True:
  7367. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7368. else:
  7369. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7370. if name:
  7371. filenames = [name]
  7372. else:
  7373. try:
  7374. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7375. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7376. except TypeError:
  7377. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7378. if len(filenames) == 0:
  7379. if silent is False:
  7380. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7381. else:
  7382. for filename in filenames:
  7383. if filename != '':
  7384. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7385. def on_filerunscript(self, name=None, silent=False):
  7386. """
  7387. File menu callback for loading and running a TCL script.
  7388. :param silent: if True will not display status messages
  7389. :param name: name of a Tcl script file to be run by FlatCAM
  7390. :return: None
  7391. """
  7392. self.app.log.debug("on_file_runscript()")
  7393. if name:
  7394. filename = name
  7395. if self.app.cmd_line_headless != 1:
  7396. self.splash.showMessage('%s: %ssec\n%s' %
  7397. (_("Canvas initialization started.\n"
  7398. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7399. _("Executing ScriptObject file.")
  7400. ),
  7401. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7402. color=QtGui.QColor("gray"))
  7403. else:
  7404. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7405. "All Files (*.*)"
  7406. try:
  7407. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7408. directory=self.app.get_last_folder(),
  7409. filter=_filter_)
  7410. except TypeError:
  7411. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7412. # The Qt methods above will return a QString which can cause problems later.
  7413. # So far json.dump() will fail to serialize it.
  7414. filename = str(filename)
  7415. if filename == "":
  7416. if silent is False:
  7417. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7418. else:
  7419. if self.app.cmd_line_headless != 1:
  7420. if self.app.ui.shell_dock.isHidden():
  7421. self.app.ui.shell_dock.show()
  7422. try:
  7423. with open(filename, "r") as tcl_script:
  7424. cmd_line_shellfile_content = tcl_script.read()
  7425. if self.app.cmd_line_headless != 1:
  7426. self.app.shell.exec_command(cmd_line_shellfile_content)
  7427. else:
  7428. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7429. if silent is False:
  7430. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7431. except Exception as e:
  7432. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7433. sys.exit(2)
  7434. def on_file_saveproject(self, silent=False):
  7435. """
  7436. Callback for menu item File->Save Project. Saves the project to
  7437. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7438. if set to None. The project is saved by calling ``self.save_project()``.
  7439. :param silent: if True will not display status messages
  7440. :return: None
  7441. """
  7442. if self.app.project_filename is None:
  7443. self.on_file_saveprojectas()
  7444. else:
  7445. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7446. if self.defaults["global_open_style"] is False:
  7447. self.app.file_opened.emit("project", self.project_filename)
  7448. self.app.file_saved.emit("project", self.project_filename)
  7449. self.app.ui.set_ui_title(name=self.app.project_filename)
  7450. self.app.should_we_save = False
  7451. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7452. """
  7453. Callback for menu item File->Save Project As... Opens a file
  7454. chooser and saves the project to the given file via
  7455. ``self.save_project()``.
  7456. :param make_copy if to be create a copy of the project; boolean
  7457. :param use_thread: if to be run in a separate thread; boolean
  7458. :param quit_action: if to be followed by quiting the application; boolean
  7459. :return: None
  7460. """
  7461. date = str(datetime.today()).rpartition('.')[0]
  7462. date = ''.join(c for c in date if c not in ':-')
  7463. date = date.replace(' ', '_')
  7464. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7465. try:
  7466. filename, _f = FCFileSaveDialog.get_saved_filename(
  7467. caption=_("Save Project As ..."),
  7468. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7469. proj=_("Project")),
  7470. ext_filter=filter_
  7471. )
  7472. except TypeError:
  7473. filename, _f = FCFileSaveDialog.get_saved_filename(
  7474. caption=_("Save Project As ..."),
  7475. ext_filter=filter_)
  7476. filename = str(filename)
  7477. if filename == '':
  7478. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7479. return
  7480. if use_thread is True:
  7481. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7482. else:
  7483. self.save_project(filename, quit_action)
  7484. # self.save_project(filename)
  7485. if self.defaults["global_open_style"] is False:
  7486. self.app.file_opened.emit("project", filename)
  7487. self.app.file_saved.emit("project", filename)
  7488. if not make_copy:
  7489. self.app.project_filename = filename
  7490. self.app.ui.set_ui_title(name=self.app.project_filename)
  7491. self.app.should_we_save = False
  7492. def on_file_save_objects_pdf(self, use_thread=True):
  7493. date = str(datetime.today()).rpartition('.')[0]
  7494. date = ''.join(c for c in date if c not in ':-')
  7495. date = date.replace(' ', '_')
  7496. try:
  7497. obj_selection = self.app.collection.get_selected()
  7498. if len(obj_selection) == 1:
  7499. obj_name = str(obj_selection[0].options['name'])
  7500. else:
  7501. obj_name = _("FlatCAM objects print")
  7502. except AttributeError as err:
  7503. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7504. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7505. return
  7506. if not obj_selection:
  7507. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7508. return
  7509. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7510. try:
  7511. filename, _f = FCFileSaveDialog.get_saved_filename(
  7512. caption=_("Save Object as PDF ..."),
  7513. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7514. obj_name=obj_name,
  7515. date=date),
  7516. ext_filter=filter_
  7517. )
  7518. except TypeError:
  7519. filename, _f = FCFileSaveDialog.get_saved_filename(
  7520. caption=_("Save Object as PDF ..."),
  7521. ext_filter=filter_)
  7522. filename = str(filename)
  7523. if filename == '':
  7524. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7525. return
  7526. if use_thread is True:
  7527. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7528. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7529. else:
  7530. self.save_pdf(filename, obj_selection)
  7531. # self.save_project(filename)
  7532. if self.defaults["global_open_style"] is False:
  7533. self.app.file_opened.emit("pdf", filename)
  7534. self.app.file_saved.emit("pdf", filename)
  7535. def save_pdf(self, file_name, obj_selection):
  7536. p_size = self.defaults['global_workspaceT']
  7537. orientation = self.defaults['global_workspace_orientation']
  7538. color = 'black'
  7539. transparency_level = 1.0
  7540. self.pagesize.update(
  7541. {
  7542. 'Bounds': None,
  7543. 'A0': (841 * mm, 1189 * mm),
  7544. 'A1': (594 * mm, 841 * mm),
  7545. 'A2': (420 * mm, 594 * mm),
  7546. 'A3': (297 * mm, 420 * mm),
  7547. 'A4': (210 * mm, 297 * mm),
  7548. 'A5': (148 * mm, 210 * mm),
  7549. 'A6': (105 * mm, 148 * mm),
  7550. 'A7': (74 * mm, 105 * mm),
  7551. 'A8': (52 * mm, 74 * mm),
  7552. 'A9': (37 * mm, 52 * mm),
  7553. 'A10': (26 * mm, 37 * mm),
  7554. 'B0': (1000 * mm, 1414 * mm),
  7555. 'B1': (707 * mm, 1000 * mm),
  7556. 'B2': (500 * mm, 707 * mm),
  7557. 'B3': (353 * mm, 500 * mm),
  7558. 'B4': (250 * mm, 353 * mm),
  7559. 'B5': (176 * mm, 250 * mm),
  7560. 'B6': (125 * mm, 176 * mm),
  7561. 'B7': (88 * mm, 125 * mm),
  7562. 'B8': (62 * mm, 88 * mm),
  7563. 'B9': (44 * mm, 62 * mm),
  7564. 'B10': (31 * mm, 44 * mm),
  7565. 'C0': (917 * mm, 1297 * mm),
  7566. 'C1': (648 * mm, 917 * mm),
  7567. 'C2': (458 * mm, 648 * mm),
  7568. 'C3': (324 * mm, 458 * mm),
  7569. 'C4': (229 * mm, 324 * mm),
  7570. 'C5': (162 * mm, 229 * mm),
  7571. 'C6': (114 * mm, 162 * mm),
  7572. 'C7': (81 * mm, 114 * mm),
  7573. 'C8': (57 * mm, 81 * mm),
  7574. 'C9': (40 * mm, 57 * mm),
  7575. 'C10': (28 * mm, 40 * mm),
  7576. # American paper sizes
  7577. 'LETTER': (8.5 * inch, 11 * inch),
  7578. 'LEGAL': (8.5 * inch, 14 * inch),
  7579. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7580. # From https://en.wikipedia.org/wiki/Paper_size
  7581. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7582. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7583. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7584. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7585. 'LEDGER': (17 * inch, 11 * inch),
  7586. }
  7587. )
  7588. exported_svg = []
  7589. for obj in obj_selection:
  7590. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7591. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7592. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7593. color = obj.fill_color[:-2]
  7594. transparency_level = obj.fill_color[-2:]
  7595. elif obj.kind.lower() == 'geometry':
  7596. color = self.defaults["global_draw_color"]
  7597. # Change the attributes of the exported SVG
  7598. # We don't need stroke-width
  7599. # We set opacity to maximum
  7600. # We set the colour to WHITE
  7601. root = ET.fromstring(svg_obj)
  7602. for child in root:
  7603. child.set('fill', str(color))
  7604. child.set('opacity', str(transparency_level))
  7605. child.set('stroke', str(color))
  7606. exported_svg.append(ET.tostring(root))
  7607. xmin = Inf
  7608. ymin = Inf
  7609. xmax = -Inf
  7610. ymax = -Inf
  7611. for obj in obj_selection:
  7612. try:
  7613. gxmin, gymin, gxmax, gymax = obj.bounds()
  7614. xmin = min([xmin, gxmin])
  7615. ymin = min([ymin, gymin])
  7616. xmax = max([xmax, gxmax])
  7617. ymax = max([ymax, gymax])
  7618. except Exception as e:
  7619. self.app.log.warning(
  7620. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7621. # Determine bounding area for svg export
  7622. bounds = [xmin, ymin, xmax, ymax]
  7623. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7624. # This contain the measure units
  7625. uom = obj_selection[0].units.lower()
  7626. # Define a boundary around SVG of about 1.0mm (~39mils)
  7627. if uom in "mm":
  7628. boundary = 1.0
  7629. else:
  7630. boundary = 0.0393701
  7631. # Convert everything to strings for use in the xml doc
  7632. svgwidth = str(size[0] + (2 * boundary))
  7633. svgheight = str(size[1] + (2 * boundary))
  7634. minx = str(bounds[0] - boundary)
  7635. miny = str(bounds[1] + boundary + size[1])
  7636. # Add a SVG Header and footer to the svg output from shapely
  7637. # The transform flips the Y Axis so that everything renders
  7638. # properly within svg apps such as inkscape
  7639. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7640. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7641. svg_header += 'width="' + svgwidth + uom + '" '
  7642. svg_header += 'height="' + svgheight + uom + '" '
  7643. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7644. svg_header += '>'
  7645. svg_header += '<g transform="scale(1,-1)">'
  7646. svg_footer = '</g> </svg>'
  7647. svg_elem = str(svg_header)
  7648. for svg_item in exported_svg:
  7649. svg_elem += str(svg_item)
  7650. svg_elem += str(svg_footer)
  7651. # Parse the xml through a xml parser just to add line feeds
  7652. # and to make it look more pretty for the output
  7653. doc = parse_xml_string(svg_elem)
  7654. doc_final = doc.toprettyxml()
  7655. try:
  7656. if self.defaults['units'].upper() == 'IN':
  7657. unit = inch
  7658. else:
  7659. unit = mm
  7660. doc_final = StringIO(doc_final)
  7661. drawing = svg2rlg(doc_final)
  7662. if p_size == 'Bounds':
  7663. renderPDF.drawToFile(drawing, file_name)
  7664. else:
  7665. if orientation == 'p':
  7666. page_size = portrait(self.pagesize[p_size])
  7667. else:
  7668. page_size = landscape(self.pagesize[p_size])
  7669. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7670. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7671. renderPDF.draw(drawing, my_canvas, 0, 0)
  7672. my_canvas.save()
  7673. except Exception as e:
  7674. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7675. return 'fail'
  7676. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7677. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7678. """
  7679. Exports a Geometry Object to an SVG file.
  7680. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7681. :param filename: Path to the SVG file to save to.
  7682. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7683. :return:
  7684. """
  7685. if filename is None:
  7686. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7687. is not None else self.defaults["global_last_folder"]
  7688. self.app.log.debug("export_svg()")
  7689. try:
  7690. obj = self.app.collection.get_by_name(str(obj_name))
  7691. except Exception:
  7692. return 'fail'
  7693. with self.app.proc_container.new(_("Exporting SVG")):
  7694. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7695. # Determine bounding area for svg export
  7696. bounds = obj.bounds()
  7697. size = obj.size()
  7698. # Convert everything to strings for use in the xml doc
  7699. svgwidth = str(size[0])
  7700. svgheight = str(size[1])
  7701. minx = str(bounds[0])
  7702. miny = str(bounds[1] - size[1])
  7703. uom = obj.units.lower()
  7704. # Add a SVG Header and footer to the svg output from shapely
  7705. # The transform flips the Y Axis so that everything renders
  7706. # properly within svg apps such as inkscape
  7707. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7708. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7709. svg_header += 'width="' + svgwidth + uom + '" '
  7710. svg_header += 'height="' + svgheight + uom + '" '
  7711. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7712. svg_header += '<g transform="scale(1,-1)">'
  7713. svg_footer = '</g> </svg>'
  7714. svg_elem = svg_header + exported_svg + svg_footer
  7715. # Parse the xml through a xml parser just to add line feeds
  7716. # and to make it look more pretty for the output
  7717. svgcode = parse_xml_string(svg_elem)
  7718. svgcode = svgcode.toprettyxml()
  7719. try:
  7720. with open(filename, 'w') as fp:
  7721. fp.write(svgcode)
  7722. except PermissionError:
  7723. self.inform.emit('[WARNING] %s' %
  7724. _("Permission denied, saving not possible.\n"
  7725. "Most likely another app is holding the file open and not accessible."))
  7726. return 'fail'
  7727. if self.defaults["global_open_style"] is False:
  7728. self.app.file_opened.emit("SVG", filename)
  7729. self.app.file_saved.emit("SVG", filename)
  7730. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7731. def on_import_preferences(self):
  7732. """
  7733. Loads the application default settings from a saved file into
  7734. ``self.defaults`` dictionary.
  7735. :return: None
  7736. """
  7737. self.app.log.debug("App.on_import_preferences()")
  7738. # Show file chooser
  7739. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7740. try:
  7741. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7742. directory=self.app.data_path,
  7743. filter=filter_)
  7744. except TypeError:
  7745. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7746. filter=filter_)
  7747. filename = str(filename)
  7748. if filename == "":
  7749. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7750. return
  7751. # Load in the defaults from the chosen file
  7752. self.defaults.load(filename=filename, inform=self.inform)
  7753. self.app.preferencesUiManager.on_preferences_edited()
  7754. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7755. def on_export_preferences(self):
  7756. """
  7757. Save the defaults dictionary to a file.
  7758. :return: None
  7759. """
  7760. self.app.log.debug("on_export_preferences()")
  7761. # defaults_file_content = None
  7762. # Show file chooser
  7763. date = str(datetime.today()).rpartition('.')[0]
  7764. date = ''.join(c for c in date if c not in ':-')
  7765. date = date.replace(' ', '_')
  7766. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7767. try:
  7768. filename, _f = FCFileSaveDialog.get_saved_filename(
  7769. caption=_("Export FlatCAM Preferences"),
  7770. directory=self.app.data_path + '/preferences_' + date,
  7771. ext_filter=filter__
  7772. )
  7773. except TypeError:
  7774. filename, _f = FCFileSaveDialog.get_saved_filename(
  7775. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7776. filename = str(filename)
  7777. if filename == "":
  7778. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7779. return 'fail'
  7780. # Update options
  7781. self.app.preferencesUiManager.defaults_read_form()
  7782. self.defaults.propagate_defaults()
  7783. # Save update options
  7784. try:
  7785. self.defaults.write(filename=filename)
  7786. except Exception:
  7787. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7788. return
  7789. if self.defaults["global_open_style"] is False:
  7790. self.app.file_opened.emit("preferences", filename)
  7791. self.app.file_saved.emit("preferences", filename)
  7792. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7793. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7794. """
  7795. Exports a Excellon Object to an Excellon file.
  7796. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7797. :param filename: Path to the Excellon file to save to.
  7798. :param local_use:
  7799. :param use_thread: if to be run in a separate thread
  7800. :return:
  7801. """
  7802. if filename is None:
  7803. if self.defaults["global_last_save_folder"]:
  7804. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7805. else:
  7806. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7807. self.app.log.debug("export_excellon()")
  7808. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7809. self.defaults["excellon_exp_decimals"]
  7810. )
  7811. if local_use is None:
  7812. try:
  7813. obj = self.app.collection.get_by_name(str(obj_name))
  7814. except Exception:
  7815. return "Could not retrieve object: %s" % obj_name
  7816. else:
  7817. obj = local_use
  7818. if not isinstance(obj, ExcellonObject):
  7819. self.inform.emit('[ERROR_NOTCL] %s' %
  7820. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7821. return
  7822. # updated units
  7823. eunits = self.defaults["excellon_exp_units"]
  7824. ewhole = self.defaults["excellon_exp_integer"]
  7825. efract = self.defaults["excellon_exp_decimals"]
  7826. ezeros = self.defaults["excellon_exp_zeros"]
  7827. eformat = self.defaults["excellon_exp_format"]
  7828. slot_type = self.defaults["excellon_exp_slot_type"]
  7829. fc_units = self.defaults['units'].upper()
  7830. if fc_units == 'MM':
  7831. factor = 1 if eunits == 'METRIC' else 0.03937
  7832. else:
  7833. factor = 25.4 if eunits == 'METRIC' else 1
  7834. def make_excellon():
  7835. try:
  7836. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7837. header = 'M48\n'
  7838. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7839. (str(self.app.version), str(self.app.version_date))
  7840. header += ';Filename: %s' % str(obj_name) + '\n'
  7841. header += ';Created on : %s' % time_str + '\n'
  7842. if eformat == 'dec':
  7843. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7844. header += eunits + '\n'
  7845. for tool in obj.tools:
  7846. if eunits == 'METRIC':
  7847. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7848. tool=str(tool),
  7849. dec=2)
  7850. else:
  7851. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7852. tool=str(tool),
  7853. dec=4)
  7854. else:
  7855. if ezeros == 'LZ':
  7856. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7857. form='ndec', e_zeros='LZ', factor=factor,
  7858. slot_type=slot_type)
  7859. header += '%s,%s\n' % (eunits, 'LZ')
  7860. header += format_exc
  7861. for tool in obj.tools:
  7862. if eunits == 'METRIC':
  7863. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7864. float(obj.tools[tool]['tooldia']) * factor,
  7865. tool=str(tool),
  7866. dec=2)
  7867. else:
  7868. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7869. float(obj.tools[tool]['tooldia']) * factor,
  7870. tool=str(tool),
  7871. dec=4)
  7872. else:
  7873. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7874. form='ndec', e_zeros='TZ', factor=factor,
  7875. slot_type=slot_type)
  7876. header += '%s,%s\n' % (eunits, 'TZ')
  7877. header += format_exc
  7878. for tool in obj.tools:
  7879. if eunits == 'METRIC':
  7880. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7881. float(obj.tools[tool]['tooldia']) * factor,
  7882. tool=str(tool),
  7883. dec=2)
  7884. else:
  7885. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7886. float(obj.tools[tool]['tooldia']) * factor,
  7887. tool=str(tool),
  7888. dec=4)
  7889. header += '%\n'
  7890. footer = 'M30\n'
  7891. exported_excellon = header
  7892. exported_excellon += excellon_code
  7893. exported_excellon += footer
  7894. if local_use is None:
  7895. try:
  7896. with open(filename, 'w') as fp:
  7897. fp.write(exported_excellon)
  7898. except PermissionError:
  7899. self.inform.emit('[WARNING] %s' %
  7900. _("Permission denied, saving not possible.\n"
  7901. "Most likely another app is holding the file open and not accessible."))
  7902. return 'fail'
  7903. if self.defaults["global_open_style"] is False:
  7904. self.app.file_opened.emit("Excellon", filename)
  7905. self.app.file_saved.emit("Excellon", filename)
  7906. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7907. else:
  7908. return exported_excellon
  7909. except Exception as e:
  7910. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7911. return 'fail'
  7912. if use_thread is True:
  7913. with self.app.proc_container.new(_("Exporting Excellon")):
  7914. def job_thread_exc(app_obj):
  7915. ret = make_excellon()
  7916. if ret == 'fail':
  7917. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7918. return
  7919. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7920. else:
  7921. eret = make_excellon()
  7922. if eret == 'fail':
  7923. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7924. return 'fail'
  7925. if local_use is not None:
  7926. return eret
  7927. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7928. """
  7929. Exports a Gerber Object to an Gerber file.
  7930. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7931. :param filename: Path to the Gerber file to save to.
  7932. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7933. When not None, the value will be the actual Gerber object for which to create
  7934. the Gerber code
  7935. :param use_thread: if to be run in a separate thread
  7936. :return:
  7937. """
  7938. if filename is None:
  7939. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7940. is not None else self.defaults["global_last_folder"]
  7941. self.app.log.debug("export_gerber()")
  7942. if local_use is None:
  7943. try:
  7944. obj = self.app.collection.get_by_name(str(obj_name))
  7945. except Exception:
  7946. return 'fail'
  7947. else:
  7948. obj = local_use
  7949. # updated units
  7950. gunits = self.defaults["gerber_exp_units"]
  7951. gwhole = self.defaults["gerber_exp_integer"]
  7952. gfract = self.defaults["gerber_exp_decimals"]
  7953. gzeros = self.defaults["gerber_exp_zeros"]
  7954. fc_units = self.defaults['units'].upper()
  7955. if fc_units == 'MM':
  7956. factor = 1 if gunits == 'MM' else 0.03937
  7957. else:
  7958. factor = 25.4 if gunits == 'MM' else 1
  7959. def make_gerber():
  7960. try:
  7961. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7962. header = 'G04*\n'
  7963. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7964. (str(self.app.version), str(self.app.version_date))
  7965. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7966. header += 'G04 Created on : %s*' % time_str + '\n'
  7967. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7968. header += "%MO{units}*%\n".format(units=gunits)
  7969. for apid in obj.apertures:
  7970. if obj.apertures[apid]['type'] == 'C':
  7971. header += "%ADD{apid}{type},{size}*%\n".format(
  7972. apid=str(apid),
  7973. type='C',
  7974. size=(factor * obj.apertures[apid]['size'])
  7975. )
  7976. elif obj.apertures[apid]['type'] == 'R':
  7977. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7978. apid=str(apid),
  7979. type='R',
  7980. width=(factor * obj.apertures[apid]['width']),
  7981. height=(factor * obj.apertures[apid]['height'])
  7982. )
  7983. elif obj.apertures[apid]['type'] == 'O':
  7984. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7985. apid=str(apid),
  7986. type='O',
  7987. width=(factor * obj.apertures[apid]['width']),
  7988. height=(factor * obj.apertures[apid]['height'])
  7989. )
  7990. header += '\n'
  7991. # obsolete units but some software may need it
  7992. if gunits == 'IN':
  7993. header += 'G70*\n'
  7994. else:
  7995. header += 'G71*\n'
  7996. # Absolute Mode
  7997. header += 'G90*\n'
  7998. header += 'G01*\n'
  7999. # positive polarity
  8000. header += '%LPD*%\n'
  8001. footer = 'M02*\n'
  8002. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8003. exported_gerber = header
  8004. exported_gerber += gerber_code
  8005. exported_gerber += footer
  8006. if local_use is None:
  8007. try:
  8008. with open(filename, 'w') as fp:
  8009. fp.write(exported_gerber)
  8010. except PermissionError:
  8011. self.inform.emit('[WARNING] %s' %
  8012. _("Permission denied, saving not possible.\n"
  8013. "Most likely another app is holding the file open and not accessible."))
  8014. return 'fail'
  8015. if self.defaults["global_open_style"] is False:
  8016. self.app.file_opened.emit("Gerber", filename)
  8017. self.app.file_saved.emit("Gerber", filename)
  8018. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8019. else:
  8020. return exported_gerber
  8021. except Exception as e:
  8022. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8023. return 'fail'
  8024. if use_thread is True:
  8025. with self.app.proc_container.new(_("Exporting Gerber")):
  8026. def job_thread_grb(app_obj):
  8027. ret = make_gerber()
  8028. if ret == 'fail':
  8029. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8030. return
  8031. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8032. else:
  8033. gret = make_gerber()
  8034. if gret == 'fail':
  8035. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8036. return 'fail'
  8037. if local_use is not None:
  8038. return gret
  8039. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  8040. """
  8041. Exports a Geometry Object to an DXF file.
  8042. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8043. :param filename: Path to the DXF file to save to.
  8044. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8045. When not None, the value will be the actual Geometry object for which to create
  8046. the Geometry/DXF code
  8047. :param use_thread: if to be run in a separate thread
  8048. :return:
  8049. """
  8050. if filename is None:
  8051. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8052. is not None else self.defaults["global_last_folder"]
  8053. self.app.log.debug("export_dxf()")
  8054. if local_use is None:
  8055. try:
  8056. obj = self.app.collection.get_by_name(str(obj_name))
  8057. except Exception:
  8058. return 'fail'
  8059. else:
  8060. obj = local_use
  8061. def make_dxf():
  8062. try:
  8063. dxf_code = obj.export_dxf()
  8064. if local_use is None:
  8065. try:
  8066. dxf_code.saveas(filename)
  8067. except PermissionError:
  8068. self.inform.emit('[WARNING] %s' %
  8069. _("Permission denied, saving not possible.\n"
  8070. "Most likely another app is holding the file open and not accessible."))
  8071. return 'fail'
  8072. if self.defaults["global_open_style"] is False:
  8073. self.app.file_opened.emit("DXF", filename)
  8074. self.app.file_saved.emit("DXF", filename)
  8075. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8076. else:
  8077. return dxf_code
  8078. except Exception as e:
  8079. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8080. return 'fail'
  8081. if use_thread is True:
  8082. with self.app.proc_container.new(_("Exporting DXF")):
  8083. def job_thread_exc(app_obj):
  8084. ret_dxf_val = make_dxf()
  8085. if ret_dxf_val == 'fail':
  8086. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8087. return
  8088. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8089. else:
  8090. ret = make_dxf()
  8091. if ret == 'fail':
  8092. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8093. return
  8094. if local_use is not None:
  8095. return ret
  8096. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8097. """
  8098. Adds a new Geometry Object to the projects and populates
  8099. it with shapes extracted from the SVG file.
  8100. :param plot: If True then the resulting object will be plotted on canvas
  8101. :param filename: Path to the SVG file.
  8102. :param geo_type: Type of FlatCAM object that will be created from SVG
  8103. :param outname: The name given to the resulting FlatCAM object
  8104. :return:
  8105. """
  8106. self.app.log.debug("App.import_svg()")
  8107. obj_type = ""
  8108. if geo_type is None or geo_type == "geometry":
  8109. obj_type = "geometry"
  8110. elif geo_type == "gerber":
  8111. obj_type = "gerber"
  8112. else:
  8113. self.inform.emit('[ERROR_NOTCL] %s' %
  8114. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8115. return
  8116. units = self.defaults['units'].upper()
  8117. def obj_init(geo_obj, app_obj):
  8118. geo_obj.import_svg(filename, obj_type, units=units)
  8119. geo_obj.multigeo = True
  8120. with open(filename) as f:
  8121. file_content = f.read()
  8122. geo_obj.source_file = file_content
  8123. # appGUI feedback
  8124. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8125. with self.app.proc_container.new(_("Importing SVG")):
  8126. # Object name
  8127. name = outname or filename.split('/')[-1].split('\\')[-1]
  8128. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8129. if ret == 'fail':
  8130. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8131. return 'fail'
  8132. # Register recent file
  8133. self.app.file_opened.emit("svg", filename)
  8134. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8135. """
  8136. Adds a new Geometry Object to the projects and populates
  8137. it with shapes extracted from the DXF file.
  8138. :param filename: Path to the DXF file.
  8139. :param geo_type: Type of FlatCAM object that will be created from DXF
  8140. :param outname: Name for the imported Geometry
  8141. :param plot: If True then the resulting object will be plotted on canvas
  8142. :return:
  8143. """
  8144. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8145. obj_type = ""
  8146. if geo_type is None or geo_type == "geometry":
  8147. obj_type = "geometry"
  8148. elif geo_type == "gerber":
  8149. obj_type = geo_type
  8150. else:
  8151. self.inform.emit('[ERROR_NOTCL] %s' %
  8152. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8153. return
  8154. units = self.defaults['units'].upper()
  8155. def obj_init(geo_obj, app_obj):
  8156. if obj_type == "geometry":
  8157. geo_obj.import_dxf_as_geo(filename, units=units)
  8158. elif obj_type == "gerber":
  8159. geo_obj.import_dxf_as_gerber(filename, units=units)
  8160. else:
  8161. return "fail"
  8162. geo_obj.multigeo = True
  8163. with open(filename) as f:
  8164. file_content = f.read()
  8165. geo_obj.source_file = file_content
  8166. # appGUI feedback
  8167. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8168. with self.app.proc_container.new(_("Importing DXF")):
  8169. # Object name
  8170. name = outname or filename.split('/')[-1].split('\\')[-1]
  8171. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8172. if ret == 'fail':
  8173. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8174. return 'fail'
  8175. # Register recent file
  8176. self.app.file_opened.emit("dxf", filename)
  8177. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8178. """
  8179. Opens a Gerber file, parses it and creates a new object for
  8180. it in the program. Thread-safe.
  8181. :param outname: Name of the resulting object. None causes the
  8182. name to be that of the file. Str.
  8183. :param filename: Gerber file filename
  8184. :type filename: str
  8185. :param plot: boolean, to plot or not the resulting object
  8186. :param from_tcl: True if run from Tcl Shell
  8187. :return: None
  8188. """
  8189. # How the object should be initialized
  8190. def obj_init(gerber_obj, app_obj):
  8191. assert isinstance(gerber_obj, GerberObject), \
  8192. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8193. # Opening the file happens here
  8194. try:
  8195. gerber_obj.parse_file(filename)
  8196. except IOError:
  8197. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8198. return "fail"
  8199. except ParseError as err:
  8200. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8201. app_obj.log.error(str(err))
  8202. return "fail"
  8203. except Exception as e:
  8204. log.debug("App.open_gerber() --> %s" % str(e))
  8205. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8206. msg += traceback.format_exc()
  8207. app_obj.inform.emit(msg)
  8208. return "fail"
  8209. if gerber_obj.is_empty():
  8210. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8211. _("Object is not Gerber file or empty. Aborting object creation."))
  8212. return "fail"
  8213. self.app.log.debug("open_gerber()")
  8214. with self.app.proc_container.new(_("Opening Gerber")):
  8215. # Object name
  8216. name = outname or filename.split('/')[-1].split('\\')[-1]
  8217. # # ## Object creation # ##
  8218. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8219. if ret_val == 'fail':
  8220. if from_tcl:
  8221. filename = self.defaults['global_tcl_path'] + '/' + name
  8222. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8223. if ret_val == 'fail':
  8224. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8225. return 'fail'
  8226. # Register recent file
  8227. self.app.file_opened.emit("gerber", filename)
  8228. # appGUI feedback
  8229. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8230. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8231. """
  8232. Opens an Excellon file, parses it and creates a new object for
  8233. it in the program. Thread-safe.
  8234. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8235. :param filename: Excellon file filename
  8236. :type filename: str
  8237. :param plot: boolean, to plot or not the resulting object
  8238. :param from_tcl: True if run from Tcl Shell
  8239. :return: None
  8240. """
  8241. self.app.log.debug("open_excellon()")
  8242. # How the object should be initialized
  8243. def obj_init(excellon_obj, app_obj):
  8244. try:
  8245. ret = excellon_obj.parse_file(filename=filename)
  8246. if ret == "fail":
  8247. app_obj.log.debug("Excellon parsing failed.")
  8248. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8249. return "fail"
  8250. except IOError:
  8251. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8252. app_obj.log.debug("Could not open Excellon object.")
  8253. return "fail"
  8254. except Exception:
  8255. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8256. msg += traceback.format_exc()
  8257. app_obj.inform.emit(msg)
  8258. return "fail"
  8259. ret = excellon_obj.create_geometry()
  8260. if ret == 'fail':
  8261. app_obj.log.debug("Could not create geometry for Excellon object.")
  8262. return "fail"
  8263. for tool in excellon_obj.tools:
  8264. if excellon_obj.tools[tool]['solid_geometry']:
  8265. return
  8266. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8267. return "fail"
  8268. with self.app.proc_container.new(_("Opening Excellon.")):
  8269. # Object name
  8270. name = outname or filename.split('/')[-1].split('\\')[-1]
  8271. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8272. if ret_val == 'fail':
  8273. if from_tcl:
  8274. filename = self.defaults['global_tcl_path'] + '/' + name
  8275. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8276. if ret_val == 'fail':
  8277. self.inform.emit('[ERROR_NOTCL] %s' %
  8278. _('Open Excellon file failed. Probable not an Excellon file.'))
  8279. return
  8280. # Register recent file
  8281. self.app.file_opened.emit("excellon", filename)
  8282. # appGUI feedback
  8283. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8284. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8285. """
  8286. Opens a G-gcode file, parses it and creates a new object for
  8287. it in the program. Thread-safe.
  8288. :param filename: G-code file filename
  8289. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8290. :param force_parsing:
  8291. :param plot: If True plot the object on canvas
  8292. :param from_tcl: True if run from Tcl Shell
  8293. :return: None
  8294. """
  8295. self.app.log.debug("open_gcode()")
  8296. # How the object should be initialized
  8297. def obj_init(job_obj, app_obj_):
  8298. """
  8299. :param job_obj: the resulting object
  8300. :type app_obj_: App
  8301. """
  8302. assert isinstance(app_obj_, App), \
  8303. "Initializer expected App, got %s" % type(app_obj_)
  8304. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8305. try:
  8306. f = open(filename)
  8307. gcode = f.read()
  8308. f.close()
  8309. except IOError:
  8310. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8311. return "fail"
  8312. job_obj.gcode = gcode
  8313. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8314. if gcode_ret == "fail":
  8315. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8316. return "fail"
  8317. job_obj.create_geometry()
  8318. with self.app.proc_container.new(_("Opening G-Code.")):
  8319. # Object name
  8320. name = outname or filename.split('/')[-1].split('\\')[-1]
  8321. # New object creation and file processing
  8322. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8323. if ret_val == 'fail':
  8324. if from_tcl:
  8325. filename = self.defaults['global_tcl_path'] + '/' + name
  8326. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8327. if ret_val == 'fail':
  8328. self.inform.emit('[ERROR_NOTCL] %s' %
  8329. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8330. "Try to load it from File menu.\n "
  8331. "Attempting to create a FlatCAM CNCJob Object from "
  8332. "G-Code file failed during processing"))
  8333. return "fail"
  8334. # Register recent file
  8335. self.app.file_opened.emit("cncjob", filename)
  8336. # appGUI feedback
  8337. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8338. def open_hpgl2(self, filename, outname=None):
  8339. """
  8340. Opens a HPGL2 file, parses it and creates a new object for
  8341. it in the program. Thread-safe.
  8342. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8343. :param filename: HPGL2 file filename
  8344. :return: None
  8345. """
  8346. filename = filename
  8347. # How the object should be initialized
  8348. def obj_init(geo_obj, app_obj):
  8349. assert isinstance(geo_obj, GeometryObject), \
  8350. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8351. # Opening the file happens here
  8352. obj = HPGL2(self)
  8353. try:
  8354. HPGL2.parse_file(obj, filename)
  8355. except IOError:
  8356. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8357. return "fail"
  8358. except ParseError as err:
  8359. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8360. app_obj.log.error(str(err))
  8361. return "fail"
  8362. except Exception as e:
  8363. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8364. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8365. msg += traceback.format_exc()
  8366. app_obj.inform.emit(msg)
  8367. return "fail"
  8368. geo_obj.multigeo = True
  8369. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8370. geo_obj.tools = deepcopy(obj.tools)
  8371. geo_obj.source_file = deepcopy(obj.source_file)
  8372. del obj
  8373. if not geo_obj.solid_geometry:
  8374. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8375. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8376. return "fail"
  8377. self.app.log.debug("open_hpgl2()")
  8378. with self.app.proc_container.new(_("Opening HPGL2")):
  8379. # Object name
  8380. name = outname or filename.split('/')[-1].split('\\')[-1]
  8381. # # ## Object creation # ##
  8382. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8383. if ret == 'fail':
  8384. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8385. return 'fail'
  8386. # Register recent file
  8387. self.app.file_opened.emit("geometry", filename)
  8388. # appGUI feedback
  8389. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8390. def open_script(self, filename, outname=None, silent=False):
  8391. """
  8392. Opens a Script file, parses it and creates a new object for
  8393. it in the program. Thread-safe.
  8394. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8395. :param filename: Script file filename
  8396. :param silent: If True there will be no messages printed to StatusBar
  8397. :return: None
  8398. """
  8399. def obj_init(script_obj, app_obj):
  8400. assert isinstance(script_obj, ScriptObject), \
  8401. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8402. if silent is False:
  8403. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8404. try:
  8405. script_obj.parse_file(filename)
  8406. except IOError:
  8407. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8408. return "fail"
  8409. except ParseError as err:
  8410. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8411. app_obj.log.error(str(err))
  8412. return "fail"
  8413. except Exception as e:
  8414. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8415. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8416. msg += traceback.format_exc()
  8417. app_obj.inform.emit(msg)
  8418. return "fail"
  8419. self.app.log.debug("open_script()")
  8420. with self.app.proc_container.new(_("Opening TCL Script...")):
  8421. # Object name
  8422. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8423. # Object creation
  8424. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8425. if ret_val == 'fail':
  8426. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8427. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8428. if ret_val == 'fail':
  8429. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8430. return 'fail'
  8431. # Register recent file
  8432. self.app.file_opened.emit("script", filename)
  8433. # appGUI feedback
  8434. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8435. def open_config_file(self, filename, run_from_arg=None):
  8436. """
  8437. Loads a config file from the specified file.
  8438. :param filename: Name of the file from which to load.
  8439. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8440. :return: None
  8441. """
  8442. self.app.log.debug("Opening config file: " + filename)
  8443. if run_from_arg:
  8444. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8445. "Canvas initialization finished in"),
  8446. '%.2f' % self.app.used_time,
  8447. _("Opening FlatCAM Config file.")),
  8448. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8449. color=QtGui.QColor("gray"))
  8450. # # add the tab if it was closed
  8451. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8452. # # first clear previous text in text editor (if any)
  8453. # self.ui.text_editor_tab.code_editor.clear()
  8454. #
  8455. # # Switch plot_area to CNCJob tab
  8456. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8457. # close the Code editor if already open
  8458. if self.app.toggle_codeeditor:
  8459. self.app.on_toggle_code_editor()
  8460. self.app.on_toggle_code_editor()
  8461. try:
  8462. if filename:
  8463. f = QtCore.QFile(filename)
  8464. if f.open(QtCore.QIODevice.ReadOnly):
  8465. stream = QtCore.QTextStream(f)
  8466. code_edited = stream.readAll()
  8467. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8468. f.close()
  8469. except IOError:
  8470. self.app.log.error("Failed to open config file: %s" % filename)
  8471. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8472. return
  8473. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8474. """
  8475. Loads a project from the specified file.
  8476. 1) Loads and parses file
  8477. 2) Registers the file as recently opened.
  8478. 3) Calls on_file_new()
  8479. 4) Updates options
  8480. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8481. 6) Calls plot_all() if plot=True
  8482. :param filename: Name of the file from which to load.
  8483. :param run_from_arg: True if run for arguments
  8484. :param plot: If True plot all objects in the project
  8485. :param cli: Run from command line
  8486. :param from_tcl: True if run from Tcl Sehll
  8487. :return: None
  8488. """
  8489. self.app.log.debug("Opening project: " + filename)
  8490. # block autosaving while a project is loaded
  8491. self.app.block_autosave = True
  8492. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8493. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8494. if cli is None:
  8495. self.app.ui.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8496. if run_from_arg:
  8497. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8498. "Canvas initialization finished in"),
  8499. '%.2f' % self.app.used_time,
  8500. _("Opening FlatCAM Project file.")),
  8501. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8502. color=QtGui.QColor("gray"))
  8503. # Open and parse an uncompressed Project file
  8504. try:
  8505. f = open(filename, 'r')
  8506. except IOError:
  8507. if from_tcl:
  8508. name = filename.split('/')[-1].split('\\')[-1]
  8509. filename = self.defaults['global_tcl_path'] + '/' + name
  8510. try:
  8511. f = open(filename, 'r')
  8512. except IOError:
  8513. self.app.log.error("Failed to open project file: %s" % filename)
  8514. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8515. return
  8516. else:
  8517. self.app.log.error("Failed to open project file: %s" % filename)
  8518. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8519. return
  8520. try:
  8521. d = json.load(f, object_hook=dict2obj)
  8522. except Exception as e:
  8523. self.app.log.error(
  8524. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8525. (filename, str(e)))
  8526. f.close()
  8527. # Open and parse a compressed Project file
  8528. try:
  8529. with lzma.open(filename) as f:
  8530. file_content = f.read().decode('utf-8')
  8531. d = json.loads(file_content, object_hook=dict2obj)
  8532. except Exception as e:
  8533. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8534. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8535. return
  8536. # Clear the current project
  8537. # # NOT THREAD SAFE # ##
  8538. if run_from_arg is True:
  8539. pass
  8540. elif cli is True:
  8541. self.app.delete_selection_shape()
  8542. else:
  8543. self.on_file_new()
  8544. # Project options
  8545. self.app.options.update(d['options'])
  8546. self.app.project_filename = filename
  8547. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8548. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8549. if cli is None:
  8550. self.app.set_screen_units(self.app.options["units"])
  8551. # Re create objects
  8552. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8553. for obj in d['objs']:
  8554. def obj_init(obj_inst, app_inst):
  8555. try:
  8556. obj_inst.from_dict(obj)
  8557. except Exception as erro:
  8558. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8559. return 'fail'
  8560. self.app.log.debug(
  8561. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8562. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8563. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8564. if cli is None:
  8565. self.app.ui.set_ui_title(name="{} {}: {}".format(
  8566. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8567. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8568. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8569. self.app.should_we_save = False
  8570. self.app.file_opened.emit("project", filename)
  8571. # restore autosaving after a project was loaded
  8572. self.app.block_autosave = False
  8573. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8574. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8575. if cli is None:
  8576. self.app.ui.set_ui_title(name=self.app.project_filename)
  8577. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8578. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8579. """
  8580. Saves the current project to the specified file.
  8581. :param filename: Name of the file in which to save.
  8582. :type filename: str
  8583. :param quit_action: if the project saving will be followed by an app quit; boolean
  8584. :param silent: if True will not display status messages
  8585. :param from_tcl True is run from Tcl Shell
  8586. :return: None
  8587. """
  8588. self.app.log.debug("save_project()")
  8589. self.app.save_in_progress = True
  8590. if from_tcl:
  8591. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8592. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8593. # Capture the latest changes
  8594. # Current object
  8595. try:
  8596. current_object = self.app.collection.get_active()
  8597. if current_object:
  8598. current_object.read_form()
  8599. except Exception as e:
  8600. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8601. # Serialize the whole project
  8602. d = {
  8603. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8604. "options": self.app.options,
  8605. "version": self.app.version
  8606. }
  8607. if self.defaults["global_save_compressed"] is True:
  8608. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8609. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8610. # # Write
  8611. f.write(g)
  8612. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8613. else:
  8614. # Open file
  8615. try:
  8616. f = open(filename, 'w')
  8617. except IOError:
  8618. self.app.log.error("Failed to open file for saving: %s", filename)
  8619. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8620. return
  8621. # Write
  8622. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8623. f.close()
  8624. # verification of the saved project
  8625. # Open and parse
  8626. try:
  8627. saved_f = open(filename, 'r')
  8628. except IOError:
  8629. if silent is False:
  8630. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8631. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8632. return
  8633. try:
  8634. saved_d = json.load(saved_f, object_hook=dict2obj)
  8635. except Exception:
  8636. if silent is False:
  8637. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8638. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8639. f.close()
  8640. return
  8641. saved_f.close()
  8642. if silent is False:
  8643. if 'version' in saved_d:
  8644. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8645. else:
  8646. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8647. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8648. tb_settings = QSettings("Open Source", "FlatCAM")
  8649. lock_state = self.app.ui.lock_action.isChecked()
  8650. tb_settings.setValue('toolbar_lock', lock_state)
  8651. # This will write the setting to the platform specific storage.
  8652. del tb_settings
  8653. # if quit:
  8654. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8655. # t.start()
  8656. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8657. def save_source_file(self, obj_name, filename):
  8658. """
  8659. Exports a FlatCAM Object to an Gerber/Excellon file.
  8660. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8661. :param filename: Path to the Gerber file to save to.
  8662. :return:
  8663. """
  8664. if filename is None:
  8665. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8666. is not None else self.defaults["global_last_folder"]
  8667. self.app.log.debug("save source file()")
  8668. obj = self.app.collection.get_by_name(obj_name)
  8669. file_string = StringIO(obj.source_file)
  8670. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8671. if file_string.getvalue() == '':
  8672. self.inform.emit('[ERROR_NOTCL] %s' %
  8673. _("Save cancelled because source file is empty. Try to export the file."))
  8674. return 'fail'
  8675. try:
  8676. with open(filename, 'w') as file:
  8677. file.writelines('G04*\n')
  8678. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8679. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8680. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8681. file.writelines('G04 Created on : %s*\n' % time_string)
  8682. for line in file_string:
  8683. file.writelines(line)
  8684. except PermissionError:
  8685. self.inform.emit('[WARNING] %s' %
  8686. _("Permission denied, saving not possible.\n"
  8687. "Most likely another app is holding the file open and not accessible."))
  8688. return 'fail'
  8689. def on_file_savedefaults(self):
  8690. """
  8691. Callback for menu item File->Save Defaults. Saves application default options
  8692. ``self.defaults`` to current_defaults.FlatConfig.
  8693. :return: None
  8694. """
  8695. self.app.preferencesUiManager.save_defaults()
  8696. # end of file