app_Main.py 468 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422
  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 Common import LoudDict
  39. from Common import color_variant
  40. from 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
  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 appParsers.ParseHPGL2 import HPGL2
  70. # FlatCAM Workers
  71. from appProcess import *
  72. from appWorkerStack import WorkerStack
  73. # FlatCAM Tools
  74. from appTools import *
  75. # FlatCAM Translation
  76. import gettext
  77. import appTranslation as fcTranslate
  78. import builtins
  79. if sys.platform == 'win32':
  80. import winreg
  81. from win32comext.shell import shell, shellcon
  82. fcTranslate.apply_language('strings')
  83. if '_' not in builtins.__dict__:
  84. _ = gettext.gettext
  85. class App(QtCore.QObject):
  86. """
  87. The main application class. The constructor starts the GUI and all other classes used by the program.
  88. """
  89. # ###############################################################################################################
  90. # ########################################## App ################################################################
  91. # ###############################################################################################################
  92. # ###############################################################################################################
  93. # ######################################### LOGGING #############################################################
  94. # ###############################################################################################################
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ###############################################################################################################
  103. # #################################### Get Cmd Line Options #####################################################
  104. # ###############################################################################################################
  105. cmd_line_shellfile = ''
  106. cmd_line_shellvar = ''
  107. cmd_line_headless = None
  108. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  109. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  110. "FlatCam.py --headless=1"
  111. try:
  112. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  113. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  114. "shellvar=",
  115. "headless=",
  116. "multiprocessing-fork="])
  117. except getopt.GetoptError:
  118. print(cmd_line_help)
  119. sys.exit(2)
  120. for opt, arg in cmd_line_options:
  121. if opt == '-h':
  122. print(cmd_line_help)
  123. sys.exit()
  124. elif opt == '--shellfile':
  125. cmd_line_shellfile = arg
  126. elif opt == '--shellvar':
  127. cmd_line_shellvar = arg
  128. elif opt == '--headless':
  129. try:
  130. cmd_line_headless = eval(arg)
  131. except NameError:
  132. pass
  133. # ###############################################################################################################
  134. # ################################### Version and VERSION DATE ##################################################
  135. # ###############################################################################################################
  136. version = "Unstable Version"
  137. # version = 8.994
  138. version_date = "2020/07/05"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by: App.info() --> Print on the status bar
  169. inform = QtCore.pyqtSignal([str], [str, bool])
  170. # Handled by: App.info_shell() --> Print on the shell
  171. inform_shell = QtCore.pyqtSignal(str)
  172. app_quit = QtCore.pyqtSignal()
  173. # General purpose background task
  174. worker_task = QtCore.pyqtSignal(dict)
  175. # File opened
  176. # Handled by:
  177. # * register_folder()
  178. # * register_recent()
  179. # Note: Setting the parameters to unicode does not seem
  180. # to have an effect. Then are received as Qstring
  181. # anyway.
  182. # File type and filename
  183. file_opened = QtCore.pyqtSignal(str, str)
  184. # File type and filename
  185. file_saved = QtCore.pyqtSignal(str, str)
  186. # Percentage of progress
  187. progress = QtCore.pyqtSignal(int)
  188. # Emitted when a new object has been added or deleted from/to the collection
  189. object_status_changed = QtCore.pyqtSignal(object, str, str)
  190. message = QtCore.pyqtSignal(str, str, str)
  191. # Emmited when shell command is finished(one command only)
  192. shell_command_finished = QtCore.pyqtSignal(object)
  193. # Emitted when multiprocess pool has been recreated
  194. pool_recreated = QtCore.pyqtSignal(object)
  195. # Emitted when an unhandled exception happens
  196. # in the worker task.
  197. thread_exception = QtCore.pyqtSignal(object)
  198. # used to signal that there are arguments for the app
  199. args_at_startup = QtCore.pyqtSignal(list)
  200. # a reusable signal to replot a list of objects
  201. # should be disconnected after use so it can be reused
  202. replot_signal = pyqtSignal(list)
  203. # signal emitted when jumping
  204. jump_signal = pyqtSignal(tuple)
  205. # signal emitted when jumping
  206. locate_signal = pyqtSignal(tuple, str)
  207. # close app signal
  208. close_app_signal = pyqtSignal()
  209. # will perform the cleanup operation after a Graceful Exit
  210. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  211. # graphic residues behind
  212. cleanup = pyqtSignal()
  213. def __init__(self, user_defaults=True):
  214. """
  215. Starts the application.
  216. :return: app
  217. :rtype: App
  218. """
  219. super().__init__()
  220. App.log.info("FlatCAM Starting...")
  221. # ############################################################################################################
  222. # ################# Setup the listening thread for another instance launching with args ######################
  223. # ############################################################################################################
  224. if sys.platform == 'win32' or sys.platform == 'linux':
  225. # make sure the thread is stored by using a self. otherwise it's garbage collected
  226. self.listen_th = QtCore.QThread()
  227. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  228. self.new_launch = ArgsThread()
  229. self.new_launch.open_signal[list].connect(self.on_startup_args)
  230. self.new_launch.moveToThread(self.listen_th)
  231. self.new_launch.start.emit()
  232. # ############################################################################################################
  233. # ########################################## OS-specific #####################################################
  234. # ############################################################################################################
  235. portable = False
  236. # Folder for user settings.
  237. if sys.platform == 'win32':
  238. if platform.architecture()[0] == '32bit':
  239. App.log.debug("Win32!")
  240. else:
  241. App.log.debug("Win64!")
  242. # #######################################################################################################
  243. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  244. # #######################################################################################################
  245. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  246. try:
  247. with open(config_file, 'r'):
  248. pass
  249. except FileNotFoundError:
  250. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  251. try:
  252. with open(config_file, 'r') as f:
  253. try:
  254. for line in f:
  255. param = str(line).replace('\n', '').rpartition('=')
  256. if param[0] == 'portable':
  257. try:
  258. portable = eval(param[2])
  259. except NameError:
  260. portable = False
  261. if param[0] == 'headless':
  262. if param[2].lower() == 'true':
  263. self.cmd_line_headless = 1
  264. else:
  265. self.cmd_line_headless = None
  266. except Exception as e:
  267. log.debug('App.__init__() -->%s' % str(e))
  268. return
  269. except FileNotFoundError as e:
  270. log.debug(str(e))
  271. pass
  272. if portable is False:
  273. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  274. else:
  275. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  276. self.os = 'windows'
  277. else: # Linux/Unix/MacOS
  278. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  279. self.os = 'unix'
  280. # ############################################################################################################
  281. # ################################# Setup folders and files ##################################################
  282. # ############################################################################################################
  283. if not os.path.exists(self.data_path):
  284. os.makedirs(self.data_path)
  285. App.log.debug('Created data folder: ' + self.data_path)
  286. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  287. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  288. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  289. if not os.path.exists(self.preprocessorpaths):
  290. os.makedirs(self.preprocessorpaths)
  291. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  292. # create geo_tools_db.FlatDB file if there is none
  293. try:
  294. f = open(self.data_path + '/geo_tools_db.FlatDB')
  295. f.close()
  296. except IOError:
  297. App.log.debug('Creating empty geo_tool_db.FlatDB')
  298. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  299. json.dump({}, f)
  300. f.close()
  301. # create current_defaults.FlatConfig file if there is none
  302. try:
  303. f = open(self.data_path + '/current_defaults.FlatConfig')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty current_defaults.FlatConfig')
  307. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # the factory defaults are written only once at the first launch of the application after installation
  311. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  312. # create a recent files json file if there is none
  313. try:
  314. f = open(self.data_path + '/recent.json')
  315. f.close()
  316. except IOError:
  317. App.log.debug('Creating empty recent.json')
  318. f = open(self.data_path + '/recent.json', 'w')
  319. json.dump([], f)
  320. f.close()
  321. # create a recent projects json file if there is none
  322. try:
  323. fp = open(self.data_path + '/recent_projects.json')
  324. fp.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent_projects.json')
  327. fp = open(self.data_path + '/recent_projects.json', 'w')
  328. json.dump([], fp)
  329. fp.close()
  330. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  331. # This will fail under cx_freeze ...
  332. self.app_home = os.path.dirname(os.path.realpath(__file__))
  333. log.debug("Application path is " + self.app_home)
  334. log.debug("Started in " + os.getcwd())
  335. # cx_freeze workaround
  336. if os.path.isfile(self.app_home):
  337. self.app_home = os.path.dirname(self.app_home)
  338. os.chdir(self.app_home)
  339. # ############################################################################################################
  340. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  341. # ############################################################################################################
  342. self.defaults = FlatCAMDefaults()
  343. self.defaults["root_folder_path"] = self.app_home
  344. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  345. if user_defaults:
  346. self.defaults.load(filename=current_defaults_path)
  347. if self.defaults['units'] == 'MM':
  348. self.decimals = int(self.defaults['decimals_metric'])
  349. else:
  350. self.decimals = int(self.defaults['decimals_inch'])
  351. if self.defaults["global_gray_icons"] is False:
  352. self.resource_location = 'assets/resources'
  353. else:
  354. self.resource_location = 'assets/resources/dark_resources'
  355. self.current_units = self.defaults['units']
  356. # ###########################################################################################################
  357. # #################################### SETUP OBJECT CLASSES #################################################
  358. # ###########################################################################################################
  359. self.setup_obj_classes()
  360. # ###########################################################################################################
  361. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  362. # ###########################################################################################################
  363. self.pool = Pool()
  364. # ###########################################################################################################
  365. # ###################################### Clear GUI Settings - once at first start ###########################
  366. # ###########################################################################################################
  367. if self.defaults["first_run"] is True:
  368. # on first run clear the previous QSettings, therefore clearing the GUI settings
  369. qsettings = QSettings("Open Source", "FlatCAM")
  370. for key in qsettings.allKeys():
  371. qsettings.remove(key)
  372. # This will write the setting to the platform specific storage.
  373. del qsettings
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  409. if theme_settings.contains("theme"):
  410. theme = theme_settings.value('theme', type=str)
  411. else:
  412. theme = 'white'
  413. if self.defaults["global_cursor_color_enabled"]:
  414. self.cursor_color_3D = self.defaults["global_cursor_color"]
  415. else:
  416. if theme == 'white':
  417. self.cursor_color_3D = 'black'
  418. else:
  419. self.cursor_color_3D = 'gray'
  420. # update the defaults dict with the setting in QSetting
  421. self.defaults['global_theme'] = theme
  422. self.ui = MainGUI(self)
  423. # set FlatCAM units in the Status bar
  424. self.set_screen_units(self.defaults['units'])
  425. # ###########################################################################################################
  426. # ########################################### AUTOSAVE SETUP ################################################
  427. # ###########################################################################################################
  428. self.block_autosave = False
  429. self.autosave_timer = QtCore.QTimer(self)
  430. self.save_project_auto_update()
  431. self.autosave_timer.timeout.connect(self.save_project_auto)
  432. # ###########################################################################################################
  433. # #################################### LOAD PREPROCESSORS ###################################################
  434. # ###########################################################################################################
  435. # ----------------------------------------- WARNING --------------------------------------------------------
  436. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  437. # That's because the number of preprocessors can vary and here the comboboxes are populated
  438. # -----------------------------------------------------------------------------------------------------------
  439. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  440. # the preprocessor file
  441. self.preprocessors = load_preprocessors(self)
  442. # make sure that always the 'default' preprocessor is the first item in the dictionary
  443. if 'default' in self.preprocessors.keys():
  444. new_ppp_dict = {}
  445. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  446. default_pp = self.preprocessors.pop('default')
  447. new_ppp_dict['default'] = default_pp
  448. # then add the rest of the keys
  449. for name, val_class in self.preprocessors.items():
  450. new_ppp_dict[name] = val_class
  451. # and now put back the ordered dict with 'default' key first
  452. self.preprocessors = new_ppp_dict
  453. # populate the Preprocessor ComboBoxes in the PREFERENCES
  454. for name in list(self.preprocessors.keys()):
  455. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  456. if name.partition('_')[0] == 'Paste':
  457. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  458. continue
  459. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  460. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  461. if name == 'hpgl':
  462. continue
  463. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  464. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  465. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  466. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  467. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  468. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  469. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  470. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  471. QtCore.Qt.ToolTipRole)
  472. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  473. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  474. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  475. QtCore.Qt.ToolTipRole)
  476. # ###########################################################################################################
  477. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  478. # ###########################################################################################################
  479. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  480. inform=self.inform)
  481. self.preferencesUiManager.defaults_write_form()
  482. # When the self.defaults dictionary changes will update the Preferences GUI forms
  483. self.defaults.set_change_callback(self.on_defaults_dict_change)
  484. # ###########################################################################################################
  485. # ##################################### FIRST RUN SECTION ###################################################
  486. # ################################ It's done only once after install #####################################
  487. # ###########################################################################################################
  488. if self.defaults["first_run"] is True:
  489. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  490. initial_lay = 'minimal'
  491. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  492. # Set the combobox in Preferences to the current layout
  493. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  494. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  495. # after the first run, this object should be False
  496. self.defaults["first_run"] = False
  497. self.preferencesUiManager.save_defaults(silent=True)
  498. # ###########################################################################################################
  499. # ############################################ Data #########################################################
  500. # ###########################################################################################################
  501. self.recent = []
  502. self.recent_projects = []
  503. self.clipboard = QtWidgets.QApplication.clipboard()
  504. self.project_filename = None
  505. self.toggle_units_ignore = False
  506. self.main_thread = QtWidgets.QApplication.instance().thread()
  507. # ###########################################################################################################
  508. # ########################################## LOAD LANGUAGES ################################################
  509. # ###########################################################################################################
  510. self.languages = fcTranslate.load_languages()
  511. for name in sorted(self.languages.values()):
  512. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  513. # ###########################################################################################################
  514. # ####################################### APPLY APP LANGUAGE ################################################
  515. # ###########################################################################################################
  516. ret_val = fcTranslate.apply_language('strings')
  517. if ret_val == "no language":
  518. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  519. log.debug("Could not find the Language files. The App strings are missing.")
  520. else:
  521. # make the current language the current selection on the language combobox
  522. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  523. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  524. # ###########################################################################################################
  525. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  526. # ###########################################################################################################
  527. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  528. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  529. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  530. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  531. self.defaults.propagate_defaults()
  532. # ###########################################################################################################
  533. # ######################################## UPDATE THE OPTIONS ###############################################
  534. # ###########################################################################################################
  535. self.options = LoudDict()
  536. # -----------------------------------------------------------------------------------------------------------
  537. # Update the self.options from the self.defaults
  538. # The self.defaults holds the application defaults while the self.options holds the object defaults
  539. # -----------------------------------------------------------------------------------------------------------
  540. # Copy app defaults to project options
  541. for def_key, def_val in self.defaults.items():
  542. self.options[def_key] = deepcopy(def_val)
  543. self.preferencesUiManager.show_preferences_gui()
  544. # ### End of Data ####
  545. # ###########################################################################################################
  546. # #################################### SETUP OBJECT COLLECTION ##############################################
  547. # ###########################################################################################################
  548. self.collection = ObjectCollection(app=self)
  549. self.ui.project_tab_layout.addWidget(self.collection.view)
  550. self.app_obj = AppObject(app=self)
  551. # ### Adjust tabs width ## ##
  552. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  553. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  554. self.collection.view.setMinimumWidth(290)
  555. self.log.debug("Finished creating Object Collection.")
  556. # ###########################################################################################################
  557. # ######################################## SETUP Plot Area ##################################################
  558. # ###########################################################################################################
  559. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  560. if self.defaults["global_graphic_engine"] == '3D':
  561. self.is_legacy = False
  562. else:
  563. self.is_legacy = True
  564. # Event signals disconnect id holders
  565. self.mp = None
  566. self.mm = None
  567. self.mr = None
  568. self.mdc = None
  569. self.mp_zc = None
  570. self.kp = None
  571. # Matplotlib axis
  572. self.axes = None
  573. if show_splash:
  574. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  575. "Canvas initialization started."),
  576. alignment=Qt.AlignBottom | Qt.AlignLeft,
  577. color=QtGui.QColor("gray"))
  578. start_plot_time = time.time() # debug
  579. self.plotcanvas = None
  580. self.app_cursor = None
  581. self.hover_shapes = None
  582. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  583. # setup the PlotCanvas
  584. self.on_plotcanvas_setup()
  585. end_plot_time = time.time()
  586. self.used_time = end_plot_time - start_plot_time
  587. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  588. if show_splash:
  589. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  590. "Canvas initialization started.\n"
  591. "Canvas initialization finished in"), '%.2f' % self.used_time),
  592. alignment=Qt.AlignBottom | Qt.AlignLeft,
  593. color=QtGui.QColor("gray"))
  594. self.ui.splitter.setStretchFactor(1, 2)
  595. # ###########################################################################################################
  596. # ############################################### SYS TRAY ##################################################
  597. # ###########################################################################################################
  598. if self.defaults["global_systray_icon"]:
  599. self.parent_w = QtWidgets.QWidget()
  600. if self.cmd_line_headless == 1:
  601. self.trayIcon = FlatCAMSystemTray(app=self,
  602. icon=QtGui.QIcon(self.resource_location +
  603. '/flatcam_icon32_green.png'),
  604. headless=True,
  605. parent=self.parent_w)
  606. else:
  607. self.trayIcon = FlatCAMSystemTray(app=self,
  608. icon=QtGui.QIcon(self.resource_location +
  609. '/flatcam_icon32_green.png'),
  610. parent=self.parent_w)
  611. # ###########################################################################################################
  612. # ############################################### Worker SETUP ##############################################
  613. # ###########################################################################################################
  614. if self.defaults["global_worker_number"]:
  615. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  616. else:
  617. self.workers = WorkerStack(workers_number=2)
  618. self.worker_task.connect(self.workers.add_task)
  619. self.log.debug("Finished creating Workers crew.")
  620. # ###########################################################################################################
  621. # ############################################# Activity Monitor ###########################################
  622. # ###########################################################################################################
  623. # self.activity_view = FlatCAMActivityView(app=self)
  624. # self.ui.infobar.addWidget(self.activity_view)
  625. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  626. # ###########################################################################################################
  627. # ############################################# Signal handling #############################################
  628. # ###########################################################################################################
  629. # ########################################## Custom signals ################################################
  630. # signal for displaying messages in status bar
  631. self.inform[str].connect(self.info)
  632. self.inform[str, bool].connect(self.info)
  633. # signal for displaying messages in the shell
  634. self.inform_shell.connect(self.info_shell)
  635. # signal to be called when the app is quiting
  636. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  637. self.message.connect(lambda: message_dialog(parent=self.ui))
  638. # self.progress.connect(self.set_progress_bar)
  639. # signals emitted when file state change
  640. self.file_opened.connect(self.register_recent)
  641. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  642. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  643. # ########################################## Standard signals ###############################################
  644. # ### Menu
  645. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  646. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  647. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  648. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  649. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  650. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  651. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  652. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  653. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  654. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  655. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  656. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  657. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  658. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  659. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  660. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  661. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  662. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  663. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  664. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  665. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  666. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  667. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  668. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  669. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  670. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  671. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  672. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  673. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  674. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  675. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  676. self.ui.menufile_exit.triggered.connect(self.final_save)
  677. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  678. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  679. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  680. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  681. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  682. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  683. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  684. self.ui.menueditdelete.triggered.connect(self.on_delete)
  685. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  686. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  687. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  688. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  689. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  690. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  691. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  692. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  693. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  694. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  695. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  696. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  697. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  698. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  699. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  700. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  701. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  702. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  703. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  704. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  705. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  706. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  707. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  708. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  709. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  710. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  711. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  712. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  713. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  714. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  715. self.ui.menuview_replot.triggered.connect(self.plot_all)
  716. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  717. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  718. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  719. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  720. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  721. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  722. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  723. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  724. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  725. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  726. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  727. self.ui.menuhelp_about.triggered.connect(self.on_about)
  728. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  729. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  730. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  731. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  732. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  733. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  734. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  735. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  736. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  737. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  738. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  739. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  740. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  741. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  742. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  743. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  744. # ToolBar signals
  745. self.connect_toolbar_signals(ui=self.ui)
  746. # Context Menu
  747. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  748. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  749. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  750. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  751. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  752. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  753. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  754. self.ui.clearplot.triggered.connect(self.clear_plots)
  755. self.ui.replot.triggered.connect(self.plot_all)
  756. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  757. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  758. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  759. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  760. self.ui.popmenu_move.triggered.connect(self.obj_move)
  761. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  762. # Project Context Menu -> Color Setting
  763. for act in self.ui.menuprojectcolor.actions():
  764. act.triggered.connect(self.on_set_color_action_triggered)
  765. # ###########################################################################################################
  766. # #################################### GUI PREFERENCES SIGNALS ##############################################
  767. # ###########################################################################################################
  768. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  769. lambda: self.on_toggle_units(no_pref=False))
  770. # ##################################### Workspace Setting Signals ###########################################
  771. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  772. self.on_workspace_modified)
  773. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  774. self.on_workspace_modified
  775. )
  776. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  777. # ###########################################################################################################
  778. # ######################################## GUI SETTINGS SIGNALS #############################################
  779. # ###########################################################################################################
  780. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  781. # ######################################## Tools related signals ############################################
  782. # portability changed signal
  783. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  784. # Object list
  785. self.object_status_changed.connect(self.collection.on_collection_updated)
  786. # when there are arguments at application startup this get launched
  787. self.args_at_startup[list].connect(self.on_startup_args)
  788. # ###########################################################################################################
  789. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  790. # ###########################################################################################################
  791. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  792. lambda: self.restore_extensions(ext_type='excellon'))
  793. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  794. lambda: self.restore_extensions(ext_type='gcode'))
  795. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  796. lambda: self.restore_extensions(ext_type='gerber'))
  797. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  798. lambda: self.delete_all_extensions(ext_type='excellon'))
  799. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  800. lambda: self.delete_all_extensions(ext_type='gcode'))
  801. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  802. lambda: self.delete_all_extensions(ext_type='gerber'))
  803. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  804. lambda: self.add_extension(ext_type='excellon'))
  805. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  806. lambda: self.add_extension(ext_type='gcode'))
  807. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  808. lambda: self.add_extension(ext_type='gerber'))
  809. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  810. lambda: self.del_extension(ext_type='excellon'))
  811. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  812. lambda: self.del_extension(ext_type='gcode'))
  813. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  814. lambda: self.del_extension(ext_type='gerber'))
  815. # connect the 'Apply' buttons from the Preferences/File Associations
  816. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  817. lambda: self.on_register_files(obj_type='excellon'))
  818. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  819. lambda: self.on_register_files(obj_type='gcode'))
  820. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  821. lambda: self.on_register_files(obj_type='gerber'))
  822. # ###########################################################################################################
  823. # ########################################### KEYWORDS SIGNALS ##############################################
  824. # ###########################################################################################################
  825. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  826. lambda: self.restore_extensions(ext_type='keyword'))
  827. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  828. lambda: self.delete_all_extensions(ext_type='keyword'))
  829. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  830. lambda: self.add_extension(ext_type='keyword'))
  831. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='keyword'))
  833. # ###########################################################################################################
  834. # ########################################### GUI SIGNALS ###################################################
  835. # ###########################################################################################################
  836. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  837. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  838. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  839. # ###########################################################################################################
  840. # ####################################### VARIOUS SIGNALS ###################################################
  841. # ###########################################################################################################
  842. # connect the abort_all_tasks related slots to the related signals
  843. self.proc_container.idle_flag.connect(self.app_is_idle)
  844. # signal emitted when a tab is closed in the Plot Area
  845. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  846. # signal to close the application
  847. self.close_app_signal.connect(self.kill_app)
  848. # ################################# FINISHED CONNECTING SIGNALS #############################################
  849. # ###########################################################################################################
  850. # ###########################################################################################################
  851. # ###########################################################################################################
  852. self.log.debug("Finished connecting Signals.")
  853. # ###########################################################################################################
  854. # ########################################## Other setups ###################################################
  855. # ###########################################################################################################
  856. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  857. # depending on from where those tools are called different actions can be done
  858. self.call_source = 'app'
  859. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  860. self.tool_tab_locked = False
  861. # decide if to show or hide the Notebook side of the screen at startup
  862. if self.defaults["global_project_at_startup"] is True:
  863. self.ui.splitter.setSizes([1, 1])
  864. else:
  865. self.ui.splitter.setSizes([0, 1])
  866. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  867. self.setup_component_editor()
  868. # ###########################################################################################################
  869. # ####################################### Auto-complete KEYWORDS ############################################
  870. # ###########################################################################################################
  871. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  872. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  873. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  874. 'export_exc',
  875. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  876. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  877. 'interiors', 'isolate', 'join_excellon',
  878. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  879. 'mirror', 'ncc',
  880. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  881. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  882. 'options', 'origin',
  883. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  884. 'save', 'save_project',
  885. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  886. 'skew', 'subtract_poly', 'subtract_rectangle',
  887. 'version', 'write_gcode'
  888. ]
  889. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  890. 'Paste_1',
  891. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  892. 'Toolchange_manual', 'True', 'Users',
  893. 'all', 'auto', 'axis',
  894. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  895. 'contour', 'default',
  896. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  897. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  898. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  899. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  900. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  901. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  902. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  903. 'spacing_columns',
  904. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  905. 'toolchange_xy', 'toolchangez', 'travelz',
  906. 'tooldia', 'use_threads', 'value',
  907. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  908. ]
  909. self.tcl_keywords = [
  910. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  911. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  912. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  913. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  914. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  915. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  916. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  917. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  918. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  919. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  920. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  921. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  922. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  923. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  924. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  925. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  926. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  927. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  928. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  929. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  930. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  931. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  932. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  933. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  934. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  935. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  936. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  937. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  938. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  939. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  940. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  941. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  942. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  943. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  944. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  945. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  946. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  947. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  948. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  949. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  950. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  951. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  952. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  953. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  954. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  955. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  956. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  957. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  958. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  959. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  960. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  961. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  962. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  963. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  964. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  965. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  966. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  967. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  968. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  969. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  970. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  971. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  972. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  973. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  974. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  975. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  976. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  977. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  978. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  979. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  980. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  981. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  982. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  983. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  984. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  985. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  986. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  987. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  988. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  989. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  990. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  991. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  992. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  993. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  994. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  995. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  996. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  997. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  998. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  999. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1000. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1001. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1002. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1003. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1004. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1005. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1006. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1007. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1008. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1009. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1010. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1011. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1012. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1013. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1014. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1015. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1016. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1017. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1018. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1019. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1020. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1021. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1022. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1023. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1024. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1025. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1026. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1027. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1028. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1029. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1030. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1031. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1032. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1033. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1034. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1035. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1036. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1037. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1038. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1039. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1040. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1041. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1042. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1043. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1044. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1045. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1046. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1047. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1048. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1049. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1050. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1051. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1052. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1053. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1054. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1055. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1056. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1057. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1058. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1059. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1060. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1061. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1062. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1063. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1064. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1065. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1066. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1067. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1068. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1069. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1070. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1071. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1072. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1073. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1074. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1075. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1076. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1077. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1078. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1079. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1080. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1081. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1082. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1083. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1084. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1085. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1086. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1087. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1088. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1089. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1090. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1091. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1092. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1093. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1094. ]
  1095. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1096. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1097. # ###########################################################################################################
  1098. # ########################################## Tools and Plugins ##############################################
  1099. # ###########################################################################################################
  1100. self.shell = None
  1101. self.dblsidedtool = None
  1102. self.distance_tool = None
  1103. self.distance_min_tool = None
  1104. self.panelize_tool = None
  1105. self.film_tool = None
  1106. self.paste_tool = None
  1107. self.calculator_tool = None
  1108. self.rules_tool = None
  1109. self.sub_tool = None
  1110. self.move_tool = None
  1111. self.cutout_tool = None
  1112. self.ncclear_tool = None
  1113. self.paint_tool = None
  1114. self.isolation_tool = None
  1115. self.drilling_tool = None
  1116. self.optimal_tool = None
  1117. self.transform_tool = None
  1118. self.properties_tool = None
  1119. self.pdf_tool = None
  1120. self.image_tool = None
  1121. self.pcb_wizard_tool = None
  1122. self.cal_exc_tool = None
  1123. self.qrcode_tool = None
  1124. self.copper_thieving_tool = None
  1125. self.fiducial_tool = None
  1126. self.edrills_tool = None
  1127. self.align_objects_tool = None
  1128. self.punch_tool = None
  1129. self.invert_tool = None
  1130. self.corners_tool = None
  1131. self.etch_tool = None
  1132. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1133. try:
  1134. self.install_tools()
  1135. except AttributeError as e:
  1136. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1137. # ###########################################################################################################
  1138. # ############################################ SETUP RECENT ITEMS ###########################################
  1139. # ###########################################################################################################
  1140. self.setup_recent_items()
  1141. # ###########################################################################################################
  1142. # ######################################### BookMarks Manager ###############################################
  1143. # ###########################################################################################################
  1144. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1145. self.install_bookmarks()
  1146. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1147. # ###########################################################################################################
  1148. # ########################################### Tools Database ################################################
  1149. # ###########################################################################################################
  1150. self.tools_db_tab = None
  1151. # ### System Font Parsing ###
  1152. # self.f_parse = ParseFont(self)
  1153. # self.parse_system_fonts()
  1154. # ###########################################################################################################
  1155. # ############################################## Shell SETUP ################################################
  1156. # ###########################################################################################################
  1157. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1158. if self.defaults["global_shell_at_startup"]:
  1159. self.ui.shell_dock.show()
  1160. else:
  1161. self.ui.shell_dock.hide()
  1162. # ###########################################################################################################
  1163. # ######################################### Check for updates ###############################################
  1164. # ###########################################################################################################
  1165. # Separate thread (Not worker)
  1166. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1167. if (self.beta is False or self.beta is None) and \
  1168. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1169. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1170. # self.thr2 = QtCore.QThread()
  1171. self.worker_task.emit({'fcn': self.version_check,
  1172. 'params': []})
  1173. # self.thr2.start(QtCore.QThread.LowPriority)
  1174. # ###########################################################################################################
  1175. # ##################################### Register files with FlatCAM; #######################################
  1176. # ################################### It works only for Windows for now ####################################
  1177. # ###########################################################################################################
  1178. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1179. self.on_register_files()
  1180. # ###########################################################################################################
  1181. # ######################################## Variables for global usage #######################################
  1182. # ###########################################################################################################
  1183. # hold the App units
  1184. self.units = 'MM'
  1185. # coordinates for relative position display
  1186. self.rel_point1 = (0, 0)
  1187. self.rel_point2 = (0, 0)
  1188. # variable to store coordinates
  1189. self.pos = (0, 0)
  1190. self.pos_canvas = (0, 0)
  1191. self.pos_jump = (0, 0)
  1192. # variable to store mouse coordinates
  1193. self.mouse = [0, 0]
  1194. # variable to store the delta positions on cavnas
  1195. self.dx = 0
  1196. self.dy = 0
  1197. # decide if we have a double click or single click
  1198. self.doubleclick = False
  1199. # store here the is_dragging value
  1200. self.event_is_dragging = False
  1201. # variable to store if a command is active (then the var is not None) and which one it is
  1202. self.command_active = None
  1203. # variable to store the status of moving selection action
  1204. # None value means that it's not an selection action
  1205. # True value = a selection from left to right
  1206. # False value = a selection from right to left
  1207. self.selection_type = None
  1208. # List to store the objects that are currently loaded in FlatCAM
  1209. # This list is updated on each object creation or object delete
  1210. self.all_objects_list = []
  1211. self.objects_under_the_click_list = []
  1212. # List to store the objects that are selected
  1213. self.sel_objects_list = []
  1214. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1215. self.key_modifiers = None
  1216. # Variable to store the status of the code editor
  1217. self.toggle_codeeditor = False
  1218. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1219. self.click_noproject = False
  1220. self.cursor = None
  1221. # Variable to store the GCODE that was edited
  1222. self.gcode_edited = ""
  1223. self.text_editor_tab = None
  1224. # reference for the self.ui.code_editor
  1225. self.reference_code_editor = None
  1226. self.script_code = ''
  1227. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1228. self.tools_db_changed_flag = False
  1229. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1230. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1231. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1232. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1233. 'tsm']
  1234. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1235. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1236. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1237. 'sbp', 'tap', 'xpi']
  1238. self.svg_list = ['svg']
  1239. self.dxf_list = ['dxf']
  1240. self.pdf_list = ['pdf']
  1241. self.prj_list = ['flatprj']
  1242. self.conf_list = ['flatconfig']
  1243. # last used filters
  1244. self.last_op_gerber_filter = None
  1245. self.last_op_excellon_filter = None
  1246. self.last_op_gcode_filter = None
  1247. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1248. # flag for polygons not cleared
  1249. self.poly_not_cleared = False
  1250. # VisPy visuals
  1251. self.isHovering = False
  1252. self.notHovering = True
  1253. # Window geometry
  1254. self.x_pos = None
  1255. self.y_pos = None
  1256. self.width = None
  1257. self.height = None
  1258. # when True, the app has to return from any thread
  1259. self.abort_flag = False
  1260. # set the value used in the Windows Title
  1261. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1262. # this holds a widget that is installed in the Plot Area when View Source option is used
  1263. self.source_editor_tab = None
  1264. self.pagesize = {}
  1265. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1266. # VisPy visuals
  1267. if self.is_legacy is False:
  1268. try:
  1269. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1270. except AttributeError:
  1271. self.tool_shapes = None
  1272. else:
  1273. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1274. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1275. # used in the delayed shutdown self.start_delayed_quit() method
  1276. self.save_timer = None
  1277. # ###########################################################################################################
  1278. # ################################## ADDING FlatCAM EDITORS section #########################################
  1279. # ###########################################################################################################
  1280. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1281. # at the first launch of the App , the editors will not be functional.
  1282. try:
  1283. self.geo_editor = AppGeoEditor(self)
  1284. except Exception as es:
  1285. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1286. try:
  1287. self.exc_editor = AppExcEditor(self)
  1288. except Exception as es:
  1289. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1290. try:
  1291. self.grb_editor = AppGerberEditor(self)
  1292. except Exception as es:
  1293. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1294. self.log.debug("Finished adding FlatCAM Editor's.")
  1295. self.set_ui_title(name=_("New Project - Not saved"))
  1296. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1297. current_platform = platform.architecture()[0]
  1298. if current_platform != '64bit':
  1299. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1300. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1301. # ###########################################################################################################
  1302. # ########################################### EXCLUSION AREAS ###############################################
  1303. # ###########################################################################################################
  1304. self.exc_areas = ExclusionAreas(app=self)
  1305. # ###########################################################################################################
  1306. # ##################################### Finished the CONSTRUCTOR ############################################
  1307. # ###########################################################################################################
  1308. App.log.debug("END of constructor. Releasing control.")
  1309. # ###########################################################################################################
  1310. # ########################################## SHOW GUI #######################################################
  1311. # ###########################################################################################################
  1312. # if the app is not started as headless, show it
  1313. if self.cmd_line_headless != 1:
  1314. if show_splash:
  1315. # finish the splash
  1316. self.splash.finish(self.ui)
  1317. mgui_settings = QSettings("Open Source", "FlatCAM")
  1318. if mgui_settings.contains("maximized_gui"):
  1319. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1320. if maximized_ui is True:
  1321. self.ui.showMaximized()
  1322. else:
  1323. self.ui.show()
  1324. else:
  1325. self.ui.show()
  1326. if self.defaults["global_systray_icon"]:
  1327. self.trayIcon.show()
  1328. else:
  1329. log.warning("******************* RUNNING HEADLESS *******************")
  1330. # ###########################################################################################################
  1331. # ######################################## START-UP ARGUMENTS ###############################################
  1332. # ###########################################################################################################
  1333. # test if the program was started with a script as parameter
  1334. if self.cmd_line_shellvar:
  1335. try:
  1336. cnt = 0
  1337. command_tcl = 0
  1338. for i in self.cmd_line_shellvar.split(','):
  1339. if i is not None:
  1340. # noinspection PyBroadException
  1341. try:
  1342. command_tcl = eval(i)
  1343. except Exception:
  1344. command_tcl = i
  1345. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1346. cnt += 1
  1347. # if there are Windows paths then replace the path separator with a Unix like one
  1348. if sys.platform == 'win32':
  1349. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1350. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1351. except Exception as ext:
  1352. print("ERROR: ", ext)
  1353. sys.exit(2)
  1354. if self.cmd_line_shellfile:
  1355. if self.cmd_line_headless != 1:
  1356. if self.ui.shell_dock.isHidden():
  1357. self.ui.shell_dock.show()
  1358. try:
  1359. with open(self.cmd_line_shellfile, "r") as myfile:
  1360. # if show_splash:
  1361. # self.splash.showMessage('%s: %ssec\n%s' % (
  1362. # _("Canvas initialization started.\n"
  1363. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1364. # _("Executing Tcl Script ...")),
  1365. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1366. # color=QtGui.QColor("gray"))
  1367. cmd_line_shellfile_text = myfile.read()
  1368. if self.cmd_line_headless != 1:
  1369. self.shell.exec_command(cmd_line_shellfile_text)
  1370. else:
  1371. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1372. except Exception as ext:
  1373. print("ERROR: ", ext)
  1374. sys.exit(2)
  1375. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1376. # the path/file_name must be enclosed in quotes if it contain spaces
  1377. if App.args:
  1378. self.args_at_startup.emit(App.args)
  1379. if self.defaults.old_defaults_found is True:
  1380. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1381. "Please reboot the application to update."))
  1382. self.defaults.old_defaults_found = False
  1383. # ######################################### INIT FINISHED #######################################################
  1384. # #################################################################################################################
  1385. # #################################################################################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. # #################################################################################################################
  1389. @staticmethod
  1390. def copy_and_overwrite(from_path, to_path):
  1391. """
  1392. From here:
  1393. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1394. :param from_path: source path
  1395. :param to_path: destination path
  1396. :return: None
  1397. """
  1398. if os.path.exists(to_path):
  1399. shutil.rmtree(to_path)
  1400. try:
  1401. shutil.copytree(from_path, to_path)
  1402. except FileNotFoundError:
  1403. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1404. shutil.copytree(from_new_path, to_path)
  1405. def on_startup_args(self, args, silent=False):
  1406. """
  1407. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1408. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1409. :param args: a list containing the application args at startup
  1410. :return: None
  1411. """
  1412. if args is not None:
  1413. args_to_process = args
  1414. else:
  1415. args_to_process = App.args
  1416. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1417. for argument in args_to_process:
  1418. if '.FlatPrj'.lower() in argument.lower():
  1419. try:
  1420. project_name = str(argument)
  1421. if project_name == "":
  1422. if silent is False:
  1423. self.inform.emit(_("Cancelled."))
  1424. else:
  1425. # self.open_project(project_name)
  1426. run_from_arg = True
  1427. # self.worker_task.emit({'fcn': self.open_project,
  1428. # 'params': [project_name, run_from_arg]})
  1429. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1430. except Exception as e:
  1431. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1432. elif '.FlatConfig'.lower() in argument.lower():
  1433. try:
  1434. file_name = str(argument)
  1435. if file_name == "":
  1436. if silent is False:
  1437. self.inform.emit(_("Open Config file failed."))
  1438. else:
  1439. run_from_arg = True
  1440. # self.worker_task.emit({'fcn': self.open_config_file,
  1441. # 'params': [file_name, run_from_arg]})
  1442. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1443. except Exception as e:
  1444. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1445. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1446. try:
  1447. file_name = str(argument)
  1448. if file_name == "":
  1449. if silent is False:
  1450. self.inform.emit(_("Open Script file failed."))
  1451. else:
  1452. if silent is False:
  1453. self.on_fileopenscript(name=file_name)
  1454. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1455. self.on_filerunscript(name=file_name)
  1456. except Exception as e:
  1457. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1458. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1459. log.debug("App.on_startup_args() --> Quit event.")
  1460. sys.exit()
  1461. elif 'save'.lower() in argument.lower():
  1462. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1463. self.preferencesUiManager.save_defaults()
  1464. else:
  1465. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1466. proc_arg = argument.lower()
  1467. for ext in exc_list:
  1468. proc_ext = ext.replace(' ', '')
  1469. proc_ext = '.%s' % proc_ext
  1470. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1471. file_name = str(argument)
  1472. if file_name == "":
  1473. if silent is False:
  1474. self.inform.emit(_("Open Excellon file failed."))
  1475. else:
  1476. self.on_fileopenexcellon(name=file_name, signal=None)
  1477. return
  1478. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1479. for ext in gco_list:
  1480. proc_ext = ext.replace(' ', '')
  1481. proc_ext = '.%s' % proc_ext
  1482. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1483. file_name = str(argument)
  1484. if file_name == "":
  1485. if silent is False:
  1486. self.inform.emit(_("Open GCode file failed."))
  1487. else:
  1488. self.on_fileopengcode(name=file_name, signal=None)
  1489. return
  1490. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1491. for ext in grb_list:
  1492. proc_ext = ext.replace(' ', '')
  1493. proc_ext = '.%s' % proc_ext
  1494. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1495. file_name = str(argument)
  1496. if file_name == "":
  1497. if silent is False:
  1498. self.inform.emit(_("Open Gerber file failed."))
  1499. else:
  1500. self.on_fileopengerber(name=file_name, signal=None)
  1501. return
  1502. # if it reached here without already returning then the app was registered with a file that it does not
  1503. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1504. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1505. # for arg in args_to_process:
  1506. # if 'FlatCAM.exe' in arg:
  1507. # continue
  1508. # else:
  1509. # sys.exit(2)
  1510. def set_ui_title(self, name):
  1511. """
  1512. Sets the title of the main window.
  1513. :param name: String that store the project path and project name
  1514. :return: None
  1515. """
  1516. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1517. (self.version,
  1518. ('BETA' if self.beta else ''),
  1519. platform.architecture()[0],
  1520. self.engine,
  1521. name)
  1522. )
  1523. def on_app_restart(self):
  1524. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1525. # be left in the SySTray
  1526. try:
  1527. self.trayIcon.hide()
  1528. except Exception:
  1529. pass
  1530. fcTranslate.restart_program(app=self)
  1531. def clear_pool(self):
  1532. """
  1533. Clear the multiprocessing pool and calls garbage collector.
  1534. :return: None
  1535. """
  1536. self.pool.close()
  1537. self.pool = Pool()
  1538. self.pool_recreated.emit(self.pool)
  1539. gc.collect()
  1540. def install_tools(self):
  1541. """
  1542. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1543. Instantiation of the Tools classes.
  1544. The order that the tools are installed is important as they can depend on each other install position.
  1545. :return: None
  1546. """
  1547. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1548. self.shell = FCShell(app=self, version=self.version)
  1549. self.distance_tool = Distance(self)
  1550. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1551. before=self.ui.menueditorigin,
  1552. separator=False)
  1553. self.distance_min_tool = DistanceMin(self)
  1554. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1555. pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=True)
  1558. self.dblsidedtool = DblSidedTool(self)
  1559. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1560. self.cal_exc_tool = ToolCalibration(self)
  1561. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1562. before=self.dblsidedtool.menuAction,
  1563. separator=False)
  1564. self.align_objects_tool = AlignObjects(self)
  1565. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1566. self.edrills_tool = ToolExtractDrills(self)
  1567. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1568. self.panelize_tool = Panelize(self)
  1569. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1570. self.film_tool = Film(self)
  1571. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1572. self.paste_tool = SolderPaste(self)
  1573. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1574. self.calculator_tool = ToolCalculator(self)
  1575. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1576. self.sub_tool = ToolSub(self)
  1577. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1578. pos=self.ui.menutool, separator=True)
  1579. self.rules_tool = RulesCheck(self)
  1580. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1581. pos=self.ui.menutool, separator=False)
  1582. self.optimal_tool = ToolOptimal(self)
  1583. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1584. pos=self.ui.menutool, separator=True)
  1585. self.move_tool = ToolMove(self)
  1586. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1587. before=self.ui.menueditorigin, separator=True)
  1588. self.cutout_tool = CutOut(self)
  1589. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction)
  1591. self.ncclear_tool = NonCopperClear(self)
  1592. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction, separator=True)
  1594. self.paint_tool = ToolPaint(self)
  1595. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1596. before=self.sub_tool.menuAction, separator=True)
  1597. self.isolation_tool = ToolIsolation(self)
  1598. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1599. before=self.sub_tool.menuAction, separator=True)
  1600. self.drilling_tool = ToolDrilling(self)
  1601. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1602. before=self.sub_tool.menuAction, separator=True)
  1603. self.copper_thieving_tool = ToolCopperThieving(self)
  1604. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1605. pos=self.ui.menutool)
  1606. self.fiducial_tool = ToolFiducials(self)
  1607. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1608. pos=self.ui.menutool)
  1609. self.qrcode_tool = QRCode(self)
  1610. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1611. pos=self.ui.menutool)
  1612. self.punch_tool = ToolPunchGerber(self)
  1613. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1614. self.invert_tool = ToolInvertGerber(self)
  1615. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1616. self.corners_tool = ToolCorners(self)
  1617. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1618. self.etch_tool = ToolEtchCompensation(self)
  1619. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1620. self.transform_tool = ToolTransform(self)
  1621. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1622. pos=self.ui.menuoptions, separator=True)
  1623. self.properties_tool = Properties(self)
  1624. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1625. pos=self.ui.menuoptions)
  1626. self.pdf_tool = ToolPDF(self)
  1627. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1628. pos=self.ui.menufileimport,
  1629. separator=True)
  1630. self.image_tool = ToolImage(self)
  1631. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1632. pos=self.ui.menufileimport,
  1633. separator=True)
  1634. self.pcb_wizard_tool = PcbWizard(self)
  1635. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1636. pos=self.ui.menufileimport)
  1637. self.log.debug("Tools are installed.")
  1638. def remove_tools(self):
  1639. """
  1640. Will remove all the actions in the Tool menu.
  1641. :return: None
  1642. """
  1643. for act in self.ui.menutool.actions():
  1644. self.ui.menutool.removeAction(act)
  1645. def init_tools(self):
  1646. """
  1647. Initialize the Tool tab in the notebook side of the central widget.
  1648. Remove the actions in the Tools menu.
  1649. Instantiate again the FlatCAM tools (plugins).
  1650. All this is required when changing the layout: standard, compact etc.
  1651. :return: None
  1652. """
  1653. log.debug("init_tools()")
  1654. # delete the data currently in the Tools Tab and the Tab itself
  1655. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1656. if widget is not None:
  1657. widget.deleteLater()
  1658. self.ui.notebook.removeTab(2)
  1659. # rebuild the Tools Tab
  1660. self.ui.tool_tab = QtWidgets.QWidget()
  1661. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1662. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1663. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1664. self.ui.tool_scroll_area = VerticalScrollArea()
  1665. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1666. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1667. # first remove all of them
  1668. self.remove_tools()
  1669. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1670. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1671. '&Command Line\tS')
  1672. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1673. # third install all of them
  1674. try:
  1675. self.install_tools()
  1676. except AttributeError:
  1677. pass
  1678. self.log.debug("Tools are initialized.")
  1679. # def parse_system_fonts(self):
  1680. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1681. # 'params': []})
  1682. def connect_tools_signals_to_toolbar(self, ui):
  1683. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1684. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1685. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1686. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1687. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1688. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1689. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1690. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1691. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1692. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1693. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1694. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1695. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1696. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1697. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1698. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1699. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1700. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1701. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1702. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1703. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1704. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1705. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1706. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1707. def connect_toolbar_signals(self, ui):
  1708. """
  1709. Reconnect the signals to the actions in the toolbar.
  1710. This has to be done each time after the FlatCAM tools are removed/installed.
  1711. :return: None
  1712. """
  1713. # Toolbar
  1714. # File Toolbar Signals
  1715. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1716. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1717. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1718. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1719. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1720. # View Toolbar Signals
  1721. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1722. ui.replot_btn.triggered.connect(self.plot_all)
  1723. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1724. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1725. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1726. # Edit Toolbar Signals
  1727. ui.editgeo_btn.triggered.connect(self.object2editor)
  1728. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1729. ui.copy_btn.triggered.connect(self.on_copy_command)
  1730. ui.delete_btn.triggered.connect(self.on_delete)
  1731. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1732. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1733. ui.origin_btn.triggered.connect(self.on_set_origin)
  1734. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1735. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1736. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1737. # Scripting Toolbar Signals
  1738. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1739. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1740. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1741. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1742. # Tools Toolbar Signals
  1743. try:
  1744. self.connect_tools_signals_to_toolbar(ui=ui)
  1745. except Exception as err:
  1746. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1747. def object2editor(self):
  1748. """
  1749. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1750. :return: None
  1751. """
  1752. self.defaults.report_usage("object2editor()")
  1753. # disable the objects menu as it may interfere with the appEditors
  1754. self.ui.menuobjects.setDisabled(True)
  1755. edited_object = self.collection.get_active()
  1756. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1757. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1758. pass
  1759. else:
  1760. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1761. return
  1762. if isinstance(edited_object, GeometryObject):
  1763. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1764. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1765. # we set the notebook to hidden
  1766. # self.ui.splitter.setSizes([0, 1])
  1767. if edited_object.multigeo is True:
  1768. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1769. if len(sel_rows) > 1:
  1770. self.inform.emit('[WARNING_NOTCL] %s' %
  1771. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1772. "is not possible.\n"
  1773. "Edit only one geometry at a time."))
  1774. if not sel_rows:
  1775. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1776. return
  1777. # determine the tool dia of the selected tool
  1778. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1779. # now find the key in the edited_object.tools that has this tooldia
  1780. multi_tool = 1
  1781. for tool in edited_object.tools:
  1782. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1783. multi_tool = tool
  1784. break
  1785. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1786. else:
  1787. self.geo_editor.edit_fcgeometry(edited_object)
  1788. # set call source to the Editor we go into
  1789. self.call_source = 'geo_editor'
  1790. elif isinstance(edited_object, ExcellonObject):
  1791. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1792. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1793. if self.ui.splitter.sizes()[0] == 0:
  1794. self.ui.splitter.setSizes([1, 1])
  1795. self.exc_editor.edit_fcexcellon(edited_object)
  1796. # set call source to the Editor we go into
  1797. self.call_source = 'exc_editor'
  1798. elif isinstance(edited_object, GerberObject):
  1799. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1800. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1801. if self.ui.splitter.sizes()[0] == 0:
  1802. self.ui.splitter.setSizes([1, 1])
  1803. self.grb_editor.edit_fcgerber(edited_object)
  1804. # set call source to the Editor we go into
  1805. self.call_source = 'grb_editor'
  1806. # reset the following variables so the UI is built again after edit
  1807. edited_object.ui_build = False
  1808. elif isinstance(edited_object, CNCJobObject):
  1809. if self.ui.splitter.sizes()[0] == 0:
  1810. self.ui.splitter.setSizes([1, 1])
  1811. edited_object.on_edit_code_click()
  1812. return
  1813. # make sure that we can't select another object while in Editor Mode:
  1814. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1815. self.ui.project_frame.setDisabled(True)
  1816. # delete any selection shape that might be active as they are not relevant in Editor
  1817. self.delete_selection_shape()
  1818. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1819. self.ui.plot_tab_area.protectTab(0)
  1820. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1821. self.should_we_save = True
  1822. def editor2object(self, cleanup=None):
  1823. """
  1824. Transfers the Geometry or Excellon from it's editor to the current object.
  1825. :return: None
  1826. """
  1827. self.defaults.report_usage("editor2object()")
  1828. # re-enable the objects menu that was disabled on entry in Editor mode
  1829. self.ui.menuobjects.setDisabled(False)
  1830. # do not update a geometry or excellon object unless it comes out of an editor
  1831. if self.call_source != 'app':
  1832. edited_obj = self.collection.get_active()
  1833. if cleanup is None:
  1834. msgbox = QtWidgets.QMessageBox()
  1835. msgbox.setText(_("Do you want to save the edited object?"))
  1836. msgbox.setWindowTitle(_("Close Editor"))
  1837. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1838. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1839. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1840. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1841. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1842. msgbox.setDefaultButton(bt_yes)
  1843. msgbox.exec_()
  1844. response = msgbox.clickedButton()
  1845. if response == bt_yes:
  1846. # clean the Tools Tab
  1847. self.ui.tool_scroll_area.takeWidget()
  1848. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1849. self.ui.notebook.setTabText(2, "Tool")
  1850. if isinstance(edited_obj, GeometryObject):
  1851. obj_type = "Geometry"
  1852. self.geo_editor.update_fcgeometry(edited_obj)
  1853. # self.geo_editor.update_options(edited_obj)
  1854. # restore GUI to the Selected TAB
  1855. # Remove anything else in the appGUI
  1856. self.ui.tool_scroll_area.takeWidget()
  1857. # update the geo object options so it is including the bounding box values
  1858. try:
  1859. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1860. edited_obj.options['xmin'] = xmin
  1861. edited_obj.options['ymin'] = ymin
  1862. edited_obj.options['xmax'] = xmax
  1863. edited_obj.options['ymax'] = ymax
  1864. except AttributeError as e:
  1865. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1866. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1867. edited_obj.build_ui()
  1868. edited_obj.plot()
  1869. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1870. elif isinstance(edited_obj, GerberObject):
  1871. obj_type = "Gerber"
  1872. self.grb_editor.update_fcgerber()
  1873. # self.grb_editor.update_options(edited_obj)
  1874. # delete the old object (the source object) if it was an empty one
  1875. try:
  1876. if len(edited_obj.solid_geometry) == 0:
  1877. old_name = edited_obj.options['name']
  1878. self.collection.delete_by_name(old_name)
  1879. except TypeError:
  1880. # if the solid_geometry is a single Polygon the len() will not work
  1881. # in any case, falling here means that we have something in the solid_geometry, even if only
  1882. # a single Polygon, therefore we pass this
  1883. pass
  1884. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1885. # restore GUI to the Selected TAB
  1886. # Remove anything else in the GUI
  1887. self.ui.selected_scroll_area.takeWidget()
  1888. elif isinstance(edited_obj, ExcellonObject):
  1889. obj_type = "Excellon"
  1890. self.exc_editor.update_fcexcellon(edited_obj)
  1891. # self.exc_editor.update_options(edited_obj)
  1892. # restore GUI to the Selected TAB
  1893. # Remove anything else in the GUI
  1894. self.ui.tool_scroll_area.takeWidget()
  1895. # delete the old object (the source object) if it was an empty one
  1896. # find if we have drills:
  1897. has_drills = None
  1898. for tt in edited_obj.tools:
  1899. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1900. has_drills = True
  1901. break
  1902. # find if we have slots:
  1903. has_slots = None
  1904. for tt in edited_obj.tools:
  1905. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1906. has_slots = True
  1907. break
  1908. if has_drills is None and has_slots is None:
  1909. old_name = edited_obj.options['name']
  1910. self.collection.delete_by_name(name=old_name)
  1911. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1912. else:
  1913. self.inform.emit('[WARNING_NOTCL] %s' %
  1914. _("Select a Gerber, Geometry or Excellon Object to update."))
  1915. return
  1916. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1917. elif response == bt_no:
  1918. # clean the Tools Tab
  1919. self.ui.tool_scroll_area.takeWidget()
  1920. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1921. self.ui.notebook.setTabText(2, "Tool")
  1922. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1923. if isinstance(edited_obj, GeometryObject):
  1924. self.geo_editor.deactivate()
  1925. edited_obj.build_ui()
  1926. edited_obj.plot()
  1927. elif isinstance(edited_obj, GerberObject):
  1928. self.grb_editor.deactivate_grb_editor()
  1929. edited_obj.build_ui()
  1930. elif isinstance(edited_obj, ExcellonObject):
  1931. self.exc_editor.deactivate()
  1932. edited_obj.build_ui()
  1933. else:
  1934. self.inform.emit('[WARNING_NOTCL] %s' %
  1935. _("Select a Gerber, Geometry or Excellon Object to update."))
  1936. return
  1937. elif response == bt_cancel:
  1938. return
  1939. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1940. # edited_obj.build_ui()
  1941. # Switch notebook to Selected page
  1942. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1943. else:
  1944. if isinstance(edited_obj, GeometryObject):
  1945. self.geo_editor.deactivate()
  1946. elif isinstance(edited_obj, GerberObject):
  1947. self.grb_editor.deactivate_grb_editor()
  1948. elif isinstance(edited_obj, ExcellonObject):
  1949. self.exc_editor.deactivate()
  1950. else:
  1951. self.inform.emit('[WARNING_NOTCL] %s' %
  1952. _("Select a Gerber, Geometry or Excellon Object to update."))
  1953. return
  1954. # if notebook is hidden we show it
  1955. if self.ui.splitter.sizes()[0] == 0:
  1956. self.ui.splitter.setSizes([1, 1])
  1957. # restore the call_source to app
  1958. self.call_source = 'app'
  1959. # edited_obj.plot()
  1960. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1961. self.ui.plot_tab_area.protectTab(0)
  1962. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1963. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1964. self.ui.project_frame.setDisabled(False)
  1965. def get_last_folder(self):
  1966. """
  1967. Get the folder path from where the last file was opened.
  1968. :return: String, last opened folder path
  1969. """
  1970. return self.defaults["global_last_folder"]
  1971. def get_last_save_folder(self):
  1972. """
  1973. Get the folder path from where the last file was saved.
  1974. :return: String, last saved folder path
  1975. """
  1976. loc = self.defaults["global_last_save_folder"]
  1977. if loc is None:
  1978. loc = self.defaults["global_last_folder"]
  1979. if loc is None:
  1980. loc = os.path.dirname(__file__)
  1981. return loc
  1982. @QtCore.pyqtSlot(str)
  1983. @QtCore.pyqtSlot(str, bool)
  1984. def info(self, msg, shell_echo=True):
  1985. """
  1986. Informs the user. Normally on the status bar, optionally
  1987. also on the shell.
  1988. :param msg: Text to write.
  1989. :type msg: str
  1990. :param shell_echo: Control if to display the message msg in the Shell
  1991. :type shell_echo: bool
  1992. :return: None
  1993. """
  1994. # Type of message in brackets at the beginning of the message.
  1995. match = re.search(r"\[(.*)\](.*)", msg)
  1996. if match:
  1997. level = match.group(1)
  1998. msg_ = match.group(2)
  1999. self.ui.fcinfo.set_status(str(msg_), level=level)
  2000. if shell_echo is True:
  2001. if level.lower() == "error":
  2002. self.shell_message(msg, error=True, show=True)
  2003. elif level.lower() == "warning":
  2004. self.shell_message(msg, warning=True, show=True)
  2005. elif level.lower() == "error_notcl":
  2006. self.shell_message(msg, error=True, show=False)
  2007. elif level.lower() == "warning_notcl":
  2008. self.shell_message(msg, warning=True, show=False)
  2009. elif level.lower() == "success":
  2010. self.shell_message(msg, success=True, show=False)
  2011. elif level.lower() == "selected":
  2012. self.shell_message(msg, selected=True, show=False)
  2013. else:
  2014. self.shell_message(msg, show=False)
  2015. else:
  2016. self.ui.fcinfo.set_status(str(msg), level="info")
  2017. # make sure that if the message is to clear the infobar with a space
  2018. # is not printed over and over on the shell
  2019. if msg != '' and shell_echo is True:
  2020. self.shell_message(msg)
  2021. def info_shell(self, msg):
  2022. self.shell_message(msg=msg)
  2023. def on_import_preferences(self):
  2024. """
  2025. Loads the application default settings from a saved file into
  2026. ``self.defaults`` dictionary.
  2027. :return: None
  2028. """
  2029. self.defaults.report_usage("on_import_preferences")
  2030. App.log.debug("App.on_import_preferences()")
  2031. # Show file chooser
  2032. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2033. try:
  2034. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2035. directory=self.data_path,
  2036. filter=filter_)
  2037. except TypeError:
  2038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2039. filter=filter_)
  2040. filename = str(filename)
  2041. if filename == "":
  2042. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2043. return
  2044. # Load in the defaults from the chosen file
  2045. self.defaults.load(filename=filename)
  2046. self.preferencesUiManager.on_preferences_edited()
  2047. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2048. def on_export_preferences(self):
  2049. """
  2050. Save the defaults dictionary to a file.
  2051. :return: None
  2052. """
  2053. self.defaults.report_usage("on_export_preferences")
  2054. App.log.debug("on_export_preferences()")
  2055. # defaults_file_content = None
  2056. # Show file chooser
  2057. date = str(datetime.today()).rpartition('.')[0]
  2058. date = ''.join(c for c in date if c not in ':-')
  2059. date = date.replace(' ', '_')
  2060. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2061. try:
  2062. filename, _f = FCFileSaveDialog.get_saved_filename(
  2063. caption=_("Export FlatCAM Preferences"),
  2064. directory=self.data_path + '/preferences_' + date,
  2065. ext_filter=filter__
  2066. )
  2067. except TypeError:
  2068. filename, _f = FCFileSaveDialog.get_saved_filename(
  2069. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2070. filename = str(filename)
  2071. if filename == "":
  2072. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2073. return
  2074. # Update options
  2075. self.preferencesUiManager.defaults_read_form()
  2076. self.defaults.propagate_defaults()
  2077. # Save update options
  2078. try:
  2079. self.defaults.write(filename=filename)
  2080. except Exception:
  2081. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2082. return
  2083. if self.defaults["global_open_style"] is False:
  2084. self.file_opened.emit("preferences", filename)
  2085. self.file_saved.emit("preferences", filename)
  2086. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2087. def save_to_file(self, content_to_save, txt_content):
  2088. """
  2089. Save something to a file.
  2090. :return: None
  2091. """
  2092. self.defaults.report_usage("save_to_file")
  2093. App.log.debug("save_to_file()")
  2094. self.date = str(datetime.today()).rpartition('.')[0]
  2095. self.date = ''.join(c for c in self.date if c not in ':-')
  2096. self.date = self.date.replace(' ', '_')
  2097. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2098. path_to_save = self.defaults["global_last_save_folder"] if \
  2099. self.defaults["global_last_save_folder"] is not None else self.data_path
  2100. try:
  2101. filename, _f = FCFileSaveDialog.get_saved_filename(
  2102. caption=_("Save to file"),
  2103. directory=path_to_save + '/file_' + self.date,
  2104. ext_filter=filter__
  2105. )
  2106. except TypeError:
  2107. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2108. filename = str(filename)
  2109. if filename == "":
  2110. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2111. return
  2112. else:
  2113. try:
  2114. with open(filename, 'w') as f:
  2115. ___ = f.read()
  2116. except PermissionError:
  2117. self.inform.emit('[WARNING] %s' %
  2118. _("Permission denied, saving not possible.\n"
  2119. "Most likely another app is holding the file open and not accessible."))
  2120. return
  2121. except IOError:
  2122. App.log.debug('Creating a new file ...')
  2123. f = open(filename, 'w')
  2124. f.close()
  2125. except Exception:
  2126. e = sys.exc_info()[0]
  2127. App.log.error("Could not load the file.")
  2128. App.log.error(str(e))
  2129. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2130. return
  2131. # Save content
  2132. if filename.rpartition('.')[2].lower() == 'html':
  2133. file_content = content_to_save
  2134. else:
  2135. file_content = txt_content
  2136. try:
  2137. with open(filename, "w") as f:
  2138. f.write(file_content)
  2139. except Exception:
  2140. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2141. return
  2142. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2143. def register_recent(self, kind, filename):
  2144. """
  2145. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2146. dictionary.
  2147. :param kind: type of file that was opened
  2148. :param filename: the path and file name for the file that was opened
  2149. :return:
  2150. """
  2151. self.log.debug("register_recent()")
  2152. self.log.debug(" %s" % kind)
  2153. self.log.debug(" %s" % filename)
  2154. record = {'kind': str(kind), 'filename': str(filename)}
  2155. if record in self.recent:
  2156. return
  2157. if record in self.recent_projects:
  2158. return
  2159. if record['kind'] == 'project':
  2160. self.recent_projects.insert(0, record)
  2161. else:
  2162. self.recent.insert(0, record)
  2163. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2164. self.recent.pop()
  2165. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2166. self.recent_projects.pop()
  2167. try:
  2168. f = open(self.data_path + '/recent.json', 'w')
  2169. except IOError:
  2170. App.log.error("Failed to open recent items file for writing.")
  2171. self.inform.emit('[ERROR_NOTCL] %s' %
  2172. _('Failed to open recent files file for writing.'))
  2173. return
  2174. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2175. f.close()
  2176. try:
  2177. fp = open(self.data_path + '/recent_projects.json', 'w')
  2178. except IOError:
  2179. App.log.error("Failed to open recent items file for writing.")
  2180. self.inform.emit('[ERROR_NOTCL] %s' %
  2181. _('Failed to open recent projects file for writing.'))
  2182. return
  2183. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2184. fp.close()
  2185. # Re-build the recent items menu
  2186. self.setup_recent_items()
  2187. def on_about(self):
  2188. """
  2189. Displays the "about" dialog found in the Menu --> Help.
  2190. :return: None
  2191. """
  2192. self.defaults.report_usage("on_about")
  2193. version = self.version
  2194. version_date = self.version_date
  2195. beta = self.beta
  2196. class AboutDialog(QtWidgets.QDialog):
  2197. def __init__(self, app, parent=None):
  2198. QtWidgets.QDialog.__init__(self, parent)
  2199. self.app = app
  2200. # Icon and title
  2201. self.setWindowIcon(parent.app_icon)
  2202. self.setWindowTitle(_("About FlatCAM"))
  2203. self.resize(600, 200)
  2204. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2205. # self.setStyleSheet(
  2206. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2207. # "background-attachment: fixed"
  2208. # )
  2209. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2210. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2211. # palette = QtGui.QPalette()
  2212. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2213. # self.setPalette(palette)
  2214. logo = QtWidgets.QLabel()
  2215. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2216. title = QtWidgets.QLabel(
  2217. "<font size=8><B>FlatCAM</B></font><BR>"
  2218. "{title}<BR>"
  2219. "<BR>"
  2220. "<BR>"
  2221. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2222. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2223. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2224. "<B>{issue}</B></a><BR>".format(
  2225. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2226. devel=_("Development"),
  2227. down=_("DOWNLOAD"),
  2228. issue=_("Issue tracker"))
  2229. )
  2230. title.setOpenExternalLinks(True)
  2231. closebtn = QtWidgets.QPushButton(_("Close"))
  2232. tab_widget = QtWidgets.QTabWidget()
  2233. description_label = QtWidgets.QLabel(
  2234. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2235. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2236. version=version,
  2237. beta=('BETA' if beta else ''),
  2238. date=version_date,
  2239. arch=platform.architecture()[0])
  2240. )
  2241. description_label.setOpenExternalLinks(True)
  2242. lic_lbl_header = QtWidgets.QLabel(
  2243. '%s:<br>%s<br>' % (
  2244. _('Licensed under the MIT license'),
  2245. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2246. "http://www.opensource.org/licenses/mit-license.php</a>"
  2247. )
  2248. )
  2249. lic_lbl_header.setOpenExternalLinks(True)
  2250. lic_lbl_body = QtWidgets.QLabel(
  2251. _(
  2252. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2253. 'of this software and associated documentation files (the "Software"), to deal\n'
  2254. 'in the Software without restriction, including without limitation the rights\n'
  2255. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2256. 'copies of the Software, and to permit persons to whom the Software is\n'
  2257. 'furnished to do so, subject to the following conditions:\n\n'
  2258. 'The above copyright notice and this permission notice shall be included in\n'
  2259. 'all copies or substantial portions of the Software.\n\n'
  2260. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2261. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2262. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2263. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2264. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2265. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2266. 'THE SOFTWARE.'
  2267. )
  2268. )
  2269. attributions_label = QtWidgets.QLabel(
  2270. _(
  2271. 'Some of the icons used are from the following sources:<br>'
  2272. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2273. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2274. 'title="Flaticon">www.flaticon.com</a></div>'
  2275. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2276. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2277. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2278. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2279. 'title="Flaticon">www.flaticon.com</a></div>'
  2280. )
  2281. )
  2282. attributions_label.setOpenExternalLinks(True)
  2283. # layouts
  2284. layout1 = QtWidgets.QVBoxLayout()
  2285. layout1_1 = QtWidgets.QHBoxLayout()
  2286. layout1_2 = QtWidgets.QHBoxLayout()
  2287. layout2 = QtWidgets.QHBoxLayout()
  2288. layout3 = QtWidgets.QHBoxLayout()
  2289. self.setLayout(layout1)
  2290. layout1.addLayout(layout1_1)
  2291. layout1.addLayout(layout1_2)
  2292. layout1.addLayout(layout2)
  2293. layout1.addLayout(layout3)
  2294. layout1_1.addStretch()
  2295. layout1_1.addWidget(description_label)
  2296. layout1_2.addWidget(tab_widget)
  2297. self.splash_tab = QtWidgets.QWidget()
  2298. self.splash_tab.setObjectName("splash_about")
  2299. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2300. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2301. tab_widget.addTab(self.splash_tab, _("Splash"))
  2302. self.programmmers_tab = QtWidgets.QWidget()
  2303. self.programmmers_tab.setObjectName("programmers_about")
  2304. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2305. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2306. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2307. self.translators_tab = QtWidgets.QWidget()
  2308. self.translators_tab.setObjectName("translators_about")
  2309. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2310. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2311. tab_widget.addTab(self.translators_tab, _("Translators"))
  2312. self.license_tab = QtWidgets.QWidget()
  2313. self.license_tab.setObjectName("license_about")
  2314. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2315. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2316. tab_widget.addTab(self.license_tab, _("License"))
  2317. self.attributions_tab = QtWidgets.QWidget()
  2318. self.attributions_tab.setObjectName("attributions_about")
  2319. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2320. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2321. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2322. self.splash_tab_layout.addWidget(logo, stretch=0)
  2323. self.splash_tab_layout.addWidget(title, stretch=1)
  2324. pal = QtGui.QPalette()
  2325. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2326. self.prog_grid_lay = QtWidgets.QGridLayout()
  2327. self.prog_grid_lay.setHorizontalSpacing(20)
  2328. self.prog_grid_lay.setColumnStretch(0, 0)
  2329. self.prog_grid_lay.setColumnStretch(2, 1)
  2330. prog_widget = QtWidgets.QWidget()
  2331. prog_widget.setLayout(self.prog_grid_lay)
  2332. prog_scroll = QtWidgets.QScrollArea()
  2333. prog_scroll.setWidget(prog_widget)
  2334. prog_scroll.setWidgetResizable(True)
  2335. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2336. prog_scroll.setPalette(pal)
  2337. self.programmmers_tab_layout.addWidget(prog_scroll)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2385. self.translator_grid_lay = QtWidgets.QGridLayout()
  2386. self.translator_grid_lay.setColumnStretch(0, 0)
  2387. self.translator_grid_lay.setColumnStretch(1, 0)
  2388. self.translator_grid_lay.setColumnStretch(2, 1)
  2389. self.translator_grid_lay.setColumnStretch(3, 0)
  2390. # trans_widget = QtWidgets.QWidget()
  2391. # trans_widget.setLayout(self.translator_grid_lay)
  2392. # self.translators_tab_layout.addWidget(trans_widget)
  2393. # self.translators_tab_layout.addStretch()
  2394. trans_widget = QtWidgets.QWidget()
  2395. trans_widget.setLayout(self.translator_grid_lay)
  2396. trans_scroll = QtWidgets.QScrollArea()
  2397. trans_scroll.setWidget(trans_widget)
  2398. trans_scroll.setWidgetResizable(True)
  2399. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2400. trans_scroll.setPalette(pal)
  2401. self.translators_tab_layout.addWidget(trans_scroll)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2404. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2405. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2406. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2407. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2408. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2409. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2411. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2430. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2431. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2432. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2433. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2438. self.translator_grid_lay.setColumnStretch(0, 0)
  2439. self.translators_tab_layout.addStretch()
  2440. self.license_tab_layout.addWidget(lic_lbl_header)
  2441. self.license_tab_layout.addWidget(lic_lbl_body)
  2442. self.license_tab_layout.addStretch()
  2443. self.attributions_tab_layout.addWidget(attributions_label)
  2444. self.attributions_tab_layout.addStretch()
  2445. layout3.addStretch()
  2446. layout3.addWidget(closebtn)
  2447. closebtn.clicked.connect(self.accept)
  2448. AboutDialog(app=self, parent=self.ui).exec_()
  2449. def on_readme(self):
  2450. """
  2451. Displays the "about" dialog found in the Menu --> Help.
  2452. :return: None
  2453. """
  2454. class ReadmeDialog(QtWidgets.QDialog):
  2455. def __init__(self, app, parent=None):
  2456. QtWidgets.QDialog.__init__(self, parent)
  2457. self.app = app
  2458. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2459. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2460. "<b>click</b></a>"
  2461. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2462. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2463. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2464. # Icon and title
  2465. self.setWindowIcon(parent.app_icon)
  2466. self.setWindowTitle(_("Important Information's"))
  2467. self.resize(750, 375)
  2468. logo = QtWidgets.QLabel()
  2469. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2470. # content = QtWidgets.QLabel(
  2471. # "%s<br>"
  2472. # "%s<br><br>"
  2473. # "%s,<br>"
  2474. # "%s<br>"
  2475. # "<ul>"
  2476. # "<li> &nbsp;%s %s</li>"
  2477. # "<li> &nbsp;%s %s</li>"
  2478. # "</ul>"
  2479. # "%s %s.<br>"
  2480. # "%s"
  2481. # "<ul>"
  2482. # "<li> &nbsp;%s &#128077;</li>"
  2483. # "<li> &nbsp;%s &#128513;</li>"
  2484. # "</ul>" %
  2485. # (
  2486. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2487. # _("Yet it cannot evolve without <b>contributions</b>."),
  2488. # _("If you want to see this application grow and become better and better"),
  2489. # _("you can <b>contribute</b> to the development yourself by:"),
  2490. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2491. # new_features_link,
  2492. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2493. # bugs_link,
  2494. # _("If you like or use this program you can make a donation"),
  2495. # donation_link,
  2496. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2497. # _("it will be welcomed with joy"),
  2498. # _("it will give me a reason to continue")
  2499. # )
  2500. # )
  2501. content = QtWidgets.QLabel(
  2502. "%s<br>"
  2503. "%s<br><br>"
  2504. "%s,<br>"
  2505. "%s<br>"
  2506. "<ul>"
  2507. "<li> &nbsp;%s %s</li>"
  2508. "<li> &nbsp;%s %s</li>"
  2509. "</ul>" %
  2510. (
  2511. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2512. _("Yet it cannot evolve without <b>contributions</b>."),
  2513. _("If you want to see this application grow and become better and better"),
  2514. _("you can <b>contribute</b> to the development yourself by:"),
  2515. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2516. new_features_link,
  2517. _("Bug Reports by providing the steps required to reproduce the bug"),
  2518. bugs_link
  2519. )
  2520. )
  2521. content.setOpenExternalLinks(True)
  2522. # palette
  2523. pal = QtGui.QPalette()
  2524. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2525. # layouts
  2526. main_layout = QtWidgets.QVBoxLayout()
  2527. self.setLayout(main_layout)
  2528. tab_layout = QtWidgets.QHBoxLayout()
  2529. buttons_hlay = QtWidgets.QHBoxLayout()
  2530. main_layout.addLayout(tab_layout)
  2531. main_layout.addLayout(buttons_hlay)
  2532. tab_widget = QtWidgets.QTabWidget()
  2533. tab_layout.addWidget(tab_widget)
  2534. closebtn = QtWidgets.QPushButton(_("Close"))
  2535. buttons_hlay.addStretch()
  2536. buttons_hlay.addWidget(closebtn)
  2537. # CONTRIBUTE section
  2538. self.intro_tab = QtWidgets.QWidget()
  2539. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2540. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2541. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2542. self.grid_lay = QtWidgets.QGridLayout()
  2543. self.grid_lay.setHorizontalSpacing(20)
  2544. self.grid_lay.setColumnStretch(0, 0)
  2545. self.grid_lay.setColumnStretch(1, 1)
  2546. intro_wdg = QtWidgets.QWidget()
  2547. intro_wdg.setLayout(self.grid_lay)
  2548. intro_scroll_area = QtWidgets.QScrollArea()
  2549. intro_scroll_area.setWidget(intro_wdg)
  2550. intro_scroll_area.setWidgetResizable(True)
  2551. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2552. intro_scroll_area.setPalette(pal)
  2553. self.grid_lay.addWidget(logo, 0, 0)
  2554. self.grid_lay.addWidget(content, 0, 1)
  2555. self.intro_tab_layout.addWidget(intro_scroll_area)
  2556. # LINKS EXCHANGE section
  2557. self.links_tab = QtWidgets.QWidget()
  2558. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2559. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2560. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2561. self.links_lay = QtWidgets.QHBoxLayout()
  2562. links_wdg = QtWidgets.QWidget()
  2563. links_wdg.setLayout(self.links_lay)
  2564. links_scroll_area = QtWidgets.QScrollArea()
  2565. links_scroll_area.setWidget(links_wdg)
  2566. links_scroll_area.setWidgetResizable(True)
  2567. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2568. links_scroll_area.setPalette(pal)
  2569. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2570. self.links_tab_layout.addWidget(links_scroll_area)
  2571. # HOW TO section
  2572. self.howto_tab = QtWidgets.QWidget()
  2573. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2574. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2575. tab_widget.addTab(self.howto_tab, _("How To's"))
  2576. self.howto_lay = QtWidgets.QHBoxLayout()
  2577. howto_wdg = QtWidgets.QWidget()
  2578. howto_wdg.setLayout(self.howto_lay)
  2579. howto_scroll_area = QtWidgets.QScrollArea()
  2580. howto_scroll_area.setWidget(howto_wdg)
  2581. howto_scroll_area.setWidgetResizable(True)
  2582. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2583. howto_scroll_area.setPalette(pal)
  2584. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2585. self.howto_tab_layout.addWidget(howto_scroll_area)
  2586. # BUTTONS section
  2587. closebtn.clicked.connect(self.accept)
  2588. ReadmeDialog(app=self, parent=self.ui).exec_()
  2589. def install_bookmarks(self, book_dict=None):
  2590. """
  2591. Install the bookmarks actions in the Help menu -> Bookmarks
  2592. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2593. :return: None
  2594. """
  2595. if book_dict is None:
  2596. self.defaults["global_bookmarks"].update(
  2597. {
  2598. '1': ['FlatCAM', "http://flatcam.org"],
  2599. '2': ['Backup Site', ""]
  2600. }
  2601. )
  2602. else:
  2603. self.defaults["global_bookmarks"].clear()
  2604. self.defaults["global_bookmarks"].update(book_dict)
  2605. # first try to disconnect if somehow they get connected from elsewhere
  2606. for act in self.ui.menuhelp_bookmarks.actions():
  2607. try:
  2608. act.triggered.disconnect()
  2609. except TypeError:
  2610. pass
  2611. # clear all actions except the last one who is the Bookmark manager
  2612. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2613. pass
  2614. else:
  2615. self.ui.menuhelp_bookmarks.removeAction(act)
  2616. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2617. if self.defaults["global_bookmarks"]:
  2618. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2619. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2620. # the JSON is first making the keys as strings (therefore I have to use strings too
  2621. # or do the conversion :(
  2622. # )
  2623. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2624. # the '10' entry jsut after '1' therefore ordering as strings
  2625. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2626. key=lambda x: int(x[0]))
  2627. for entry, bookmark in sorted_bookmarks:
  2628. title = bookmark[0]
  2629. weblink = bookmark[1]
  2630. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2631. act.setText(title)
  2632. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2633. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2634. if title == 'Backup Site' and weblink == "":
  2635. act.triggered.connect(self.on_backup_site)
  2636. else:
  2637. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2638. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2639. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2640. def on_bookmarks_manager(self):
  2641. """
  2642. Adds the bookmark manager in a Tab in Plot Area
  2643. :return:
  2644. """
  2645. for idx in range(self.ui.plot_tab_area.count()):
  2646. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2647. # there can be only one instance of Bookmark Manager at one time
  2648. return
  2649. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2650. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2651. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2652. # add the tab if it was closed
  2653. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2654. # delete the absolute and relative position and messages in the infobar
  2655. # self.ui.position_label.setText("")
  2656. # self.ui.rel_position_label.setText("")
  2657. # hide coordinates toolbars in the infobar while in DB
  2658. self.ui.coords_toolbar.hide()
  2659. self.ui.delta_coords_toolbar.hide()
  2660. # Switch plot_area to preferences page
  2661. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2662. def on_backup_site(self):
  2663. msgbox = QtWidgets.QMessageBox()
  2664. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2665. "1. FlatCAM.org website is down\n"
  2666. "2. Someone forked FlatCAM project and wants to point\n"
  2667. "to his own website\n\n"
  2668. "If you can't get any informations about FlatCAM beta\n"
  2669. "use the YouTube channel link from the Help menu."))
  2670. msgbox.setWindowTitle(_("Alternative website"))
  2671. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2672. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2673. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2674. msgbox.setDefaultButton(bt_yes)
  2675. msgbox.exec_()
  2676. # response = msgbox.clickedButton()
  2677. def on_file_savedefaults(self):
  2678. """
  2679. Callback for menu item File->Save Defaults. Saves application default options
  2680. ``self.defaults`` to current_defaults.FlatConfig.
  2681. :return: None
  2682. """
  2683. self.preferencesUiManager.save_defaults()
  2684. def final_save(self):
  2685. """
  2686. Callback for doing a preferences save to file whenever the application is about to quit.
  2687. If the project has changes, it will ask the user to save the project.
  2688. :return: None
  2689. """
  2690. if self.save_in_progress:
  2691. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2692. return
  2693. if self.should_we_save and self.collection.get_list():
  2694. msgbox = QtWidgets.QMessageBox()
  2695. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2696. "\n"
  2697. "Do you want to Save the project?"))
  2698. msgbox.setWindowTitle(_("Save changes"))
  2699. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2700. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2701. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2702. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2703. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2704. msgbox.setDefaultButton(bt_yes)
  2705. msgbox.exec_()
  2706. response = msgbox.clickedButton()
  2707. if response == bt_yes:
  2708. try:
  2709. self.trayIcon.hide()
  2710. except Exception:
  2711. pass
  2712. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2713. elif response == bt_no:
  2714. try:
  2715. self.trayIcon.hide()
  2716. except Exception:
  2717. pass
  2718. self.quit_application()
  2719. elif response == bt_cancel:
  2720. return
  2721. else:
  2722. try:
  2723. self.trayIcon.hide()
  2724. except Exception:
  2725. pass
  2726. self.quit_application()
  2727. def quit_application(self):
  2728. """
  2729. Called (as a pyslot or not) when the application is quit.
  2730. :return: None
  2731. """
  2732. # close editors before quiting the app, if they are open
  2733. if self.geo_editor.editor_active is True:
  2734. self.geo_editor.deactivate()
  2735. try:
  2736. self.geo_editor.disconnect()
  2737. except TypeError:
  2738. pass
  2739. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2740. if self.exc_editor.editor_active is True:
  2741. self.exc_editor.deactivate()
  2742. try:
  2743. self.grb_editor.disconnect()
  2744. except TypeError:
  2745. pass
  2746. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2747. if self.grb_editor.editor_active is True:
  2748. self.grb_editor.deactivate_grb_editor()
  2749. try:
  2750. self.exc_editor.disconnect()
  2751. except TypeError:
  2752. pass
  2753. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2754. # disconnect the mouse events
  2755. if self.is_legacy:
  2756. self.plotcanvas.graph_event_disconnect(self.mm)
  2757. self.plotcanvas.graph_event_disconnect(self.mp)
  2758. self.plotcanvas.graph_event_disconnect(self.mr)
  2759. self.plotcanvas.graph_event_disconnect(self.mdc)
  2760. self.plotcanvas.graph_event_disconnect(self.kp)
  2761. else:
  2762. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2763. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2764. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2765. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2766. self.on_mouse_double_click_over_plot)
  2767. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2768. self.preferencesUiManager.save_defaults(silent=True)
  2769. log.debug("App.quit_application() --> App Defaults saved.")
  2770. if self.cmd_line_headless != 1:
  2771. # save app state to file
  2772. stgs = QSettings("Open Source", "FlatCAM")
  2773. stgs.setValue('saved_gui_state', self.ui.saveState())
  2774. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2775. stgs.setValue(
  2776. 'language',
  2777. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2778. )
  2779. stgs.setValue(
  2780. 'notebook_font_size',
  2781. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2782. )
  2783. stgs.setValue(
  2784. 'axis_font_size',
  2785. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2786. )
  2787. stgs.setValue(
  2788. 'textbox_font_size',
  2789. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2790. )
  2791. stgs.setValue(
  2792. 'hud_font_size',
  2793. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2794. )
  2795. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2796. stgs.setValue(
  2797. 'machinist',
  2798. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2799. )
  2800. # This will write the setting to the platform specific storage.
  2801. del stgs
  2802. log.debug("App.quit_application() --> App UI state saved.")
  2803. # try to quit the Socket opened by ArgsThread class
  2804. try:
  2805. # self.new_launch.thread_exit = True
  2806. # self.new_launch.listener.close()
  2807. self.new_launch.stop.emit()
  2808. except Exception as err:
  2809. log.debug("App.quit_application() --> %s" % str(err))
  2810. # try to quit the QThread that run ArgsThread class
  2811. try:
  2812. # del self.new_launch
  2813. self.listen_th.quit()
  2814. except Exception as e:
  2815. log.debug("App.quit_application() --> %s" % str(e))
  2816. # terminate workers
  2817. # self.workers.__del__()
  2818. self.clear_pool()
  2819. # quit app by signalling for self.kill_app() method
  2820. # self.close_app_signal.emit()
  2821. QtWidgets.qApp.quit()
  2822. sys.exit(0)
  2823. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2824. # we use the following command
  2825. # minor_v = sys.version_info.minor
  2826. # if minor_v < 8:
  2827. # # make sure that the app closes
  2828. # sys.exit(0)
  2829. # else:
  2830. # os._exit(0) # fix to work with Python 3.8
  2831. @staticmethod
  2832. def kill_app():
  2833. QtWidgets.qApp.quit()
  2834. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2835. # we use the following command
  2836. sys.exit(0)
  2837. def on_portable_checked(self, state):
  2838. """
  2839. Callback called when the checkbox in Preferences GUI is checked.
  2840. It will set the application as portable by creating the preferences and recent files in the
  2841. 'config' folder found in the FlatCAM installation folder.
  2842. :param state: boolean, the state of the checkbox when clicked/checked
  2843. :return:
  2844. """
  2845. line_no = 0
  2846. data = None
  2847. if sys.platform != 'win32':
  2848. # this won't work in Linux or MacOS
  2849. return
  2850. # test if the app was frozen and choose the path for the configuration file
  2851. if getattr(sys, "frozen", False) is True:
  2852. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2853. else:
  2854. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2855. config_file = current_data_path + '\\configuration.txt'
  2856. try:
  2857. with open(config_file, 'r') as f:
  2858. try:
  2859. data = f.readlines()
  2860. except Exception as e:
  2861. log.debug('App.__init__() -->%s' % str(e))
  2862. return
  2863. except FileNotFoundError:
  2864. pass
  2865. for line in data:
  2866. line = line.strip('\n')
  2867. param = str(line).rpartition('=')
  2868. if param[0] == 'portable':
  2869. break
  2870. line_no += 1
  2871. if state:
  2872. data[line_no] = 'portable=True\n'
  2873. # create the new defauults files
  2874. # create current_defaults.FlatConfig file if there is none
  2875. try:
  2876. f = open(current_data_path + '/current_defaults.FlatConfig')
  2877. f.close()
  2878. except IOError:
  2879. App.log.debug('Creating empty current_defaults.FlatConfig')
  2880. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2881. json.dump({}, f)
  2882. f.close()
  2883. # create factory_defaults.FlatConfig file if there is none
  2884. try:
  2885. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2886. f.close()
  2887. except IOError:
  2888. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2889. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2890. json.dump({}, f)
  2891. f.close()
  2892. try:
  2893. f = open(current_data_path + '/recent.json')
  2894. f.close()
  2895. except IOError:
  2896. App.log.debug('Creating empty recent.json')
  2897. f = open(current_data_path + '/recent.json', 'w')
  2898. json.dump([], f)
  2899. f.close()
  2900. try:
  2901. fp = open(current_data_path + '/recent_projects.json')
  2902. fp.close()
  2903. except IOError:
  2904. App.log.debug('Creating empty recent_projects.json')
  2905. fp = open(current_data_path + '/recent_projects.json', 'w')
  2906. json.dump([], fp)
  2907. fp.close()
  2908. # save the current defaults to the new defaults file
  2909. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2910. else:
  2911. data[line_no] = 'portable=False\n'
  2912. with open(config_file, 'w') as f:
  2913. f.writelines(data)
  2914. def on_register_files(self, obj_type=None):
  2915. """
  2916. Called whenever there is a need to register file extensions with FlatCAM.
  2917. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2918. :param obj_type: the type of object to be register for.
  2919. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2920. :return: None
  2921. """
  2922. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2923. new_reg_path = 'Software\\Classes\\'
  2924. # find if the current user is admin
  2925. try:
  2926. is_admin = os.getuid() == 0
  2927. except AttributeError:
  2928. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2929. if is_admin is True:
  2930. root_path = winreg.HKEY_LOCAL_MACHINE
  2931. else:
  2932. root_path = winreg.HKEY_CURRENT_USER
  2933. # create the keys
  2934. def set_reg(name, root_pth, new_reg_path, value):
  2935. try:
  2936. winreg.CreateKey(root_pth, new_reg_path)
  2937. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2938. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2939. return True
  2940. except WindowsError:
  2941. return False
  2942. # delete key in registry
  2943. def delete_reg(root_pth, reg_path, key_to_del):
  2944. key_to_del_path = reg_path + key_to_del
  2945. try:
  2946. winreg.DeleteKey(root_pth, key_to_del_path)
  2947. return True
  2948. except WindowsError:
  2949. return False
  2950. if obj_type is None or obj_type == 'excellon':
  2951. exc_list = \
  2952. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2953. exc_list = [x for x in exc_list if x != '']
  2954. # register all keys in the Preferences window
  2955. for ext in exc_list:
  2956. new_k = new_reg_path + '.%s' % ext
  2957. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2958. # and unregister those that are no longer in the Preferences windows but are in the file
  2959. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2960. if ext not in exc_list:
  2961. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2962. # now write the updated extensions to the self.defaults
  2963. # new_ext = ''
  2964. # for ext in exc_list:
  2965. # new_ext = new_ext + ext + ', '
  2966. # self.defaults["fa_excellon"] = new_ext
  2967. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2968. if obj_type is None or obj_type == 'gcode':
  2969. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2970. gco_list = [x for x in gco_list if x != '']
  2971. # register all keys in the Preferences window
  2972. for ext in gco_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_gcode"].replace(' ', '').split(','):
  2977. if ext not in gco_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 gco_list:
  2982. # new_ext = new_ext + ext + ', '
  2983. # self.defaults["fa_gcode"] = new_ext
  2984. self.inform.emit('[success] %s' %
  2985. _("Selected GCode file extensions registered with FlatCAM."))
  2986. if obj_type is None or obj_type == 'gerber':
  2987. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2988. grb_list = [x for x in grb_list if x != '']
  2989. # register all keys in the Preferences window
  2990. for ext in grb_list:
  2991. new_k = new_reg_path + '.%s' % ext
  2992. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2993. # and unregister those that are no longer in the Preferences windows but are in the file
  2994. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2995. if ext not in grb_list:
  2996. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2997. # now write the updated extensions to the self.defaults
  2998. # new_ext = ''
  2999. # for ext in grb_list:
  3000. # new_ext = new_ext + ext + ', '
  3001. # self.defaults["fa_gerber"] = new_ext
  3002. self.inform.emit('[success] %s' %
  3003. _("Selected Gerber file extensions registered with FlatCAM."))
  3004. def add_extension(self, ext_type):
  3005. """
  3006. Add a file extension to the list for a specific object
  3007. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3008. :return:
  3009. """
  3010. if ext_type == 'excellon':
  3011. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3012. if new_ext == '':
  3013. return
  3014. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3015. if new_ext in old_val:
  3016. return
  3017. old_val.append(new_ext)
  3018. old_val.sort()
  3019. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3020. if ext_type == 'gcode':
  3021. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3022. if new_ext == '':
  3023. return
  3024. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3025. if new_ext in old_val:
  3026. return
  3027. old_val.append(new_ext)
  3028. old_val.sort()
  3029. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3030. if ext_type == 'gerber':
  3031. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3032. if new_ext == '':
  3033. return
  3034. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3035. if new_ext in old_val:
  3036. return
  3037. old_val.append(new_ext)
  3038. old_val.sort()
  3039. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3040. if ext_type == 'keyword':
  3041. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3042. if new_kw == '':
  3043. return
  3044. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3045. if new_kw in old_val:
  3046. return
  3047. old_val.append(new_kw)
  3048. old_val.sort()
  3049. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3050. # update the self.myKeywords so the model is updated
  3051. self.autocomplete_kw_list = \
  3052. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3053. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3054. self.shell._edit.set_model_data(self.myKeywords)
  3055. def del_extension(self, ext_type):
  3056. """
  3057. Remove a file extension from the list for a specific object
  3058. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3059. :return:
  3060. """
  3061. if ext_type == 'excellon':
  3062. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3063. if new_ext == '':
  3064. return
  3065. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3066. if new_ext not in old_val:
  3067. return
  3068. old_val.remove(new_ext)
  3069. old_val.sort()
  3070. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3071. if ext_type == 'gcode':
  3072. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3073. if new_ext == '':
  3074. return
  3075. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3076. if new_ext not in old_val:
  3077. return
  3078. old_val.remove(new_ext)
  3079. old_val.sort()
  3080. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3081. if ext_type == 'gerber':
  3082. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3083. if new_ext == '':
  3084. return
  3085. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3086. if new_ext not in old_val:
  3087. return
  3088. old_val.remove(new_ext)
  3089. old_val.sort()
  3090. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3091. if ext_type == 'keyword':
  3092. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3093. if new_kw == '':
  3094. return
  3095. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3096. if new_kw not in old_val:
  3097. return
  3098. old_val.remove(new_kw)
  3099. old_val.sort()
  3100. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3101. # update the self.myKeywords so the model is updated
  3102. self.autocomplete_kw_list = \
  3103. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3104. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3105. self.shell._edit.set_model_data(self.myKeywords)
  3106. def restore_extensions(self, ext_type):
  3107. """
  3108. Restore all file extensions associations with FlatCAM, for a specific object
  3109. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3110. :return:
  3111. """
  3112. if ext_type == 'excellon':
  3113. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3114. # for the ability to open Excellon files with .txt extension
  3115. new_exc_list = deepcopy(self.exc_list)
  3116. try:
  3117. new_exc_list.remove('txt')
  3118. except ValueError:
  3119. pass
  3120. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3121. if ext_type == 'gcode':
  3122. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3123. if ext_type == 'gerber':
  3124. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3125. if ext_type == 'keyword':
  3126. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3127. # update the self.myKeywords so the model is updated
  3128. self.autocomplete_kw_list = self.default_keywords
  3129. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3130. self.shell._edit.set_model_data(self.myKeywords)
  3131. def delete_all_extensions(self, ext_type):
  3132. """
  3133. Delete all file extensions associations with FlatCAM, for a specific object
  3134. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3135. :return:
  3136. """
  3137. if ext_type == 'excellon':
  3138. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3139. if ext_type == 'gcode':
  3140. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3141. if ext_type == 'gerber':
  3142. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3143. if ext_type == 'keyword':
  3144. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3145. # update the self.myKeywords so the model is updated
  3146. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3147. self.shell._edit.set_model_data(self.myKeywords)
  3148. def on_edit_join(self, name=None):
  3149. """
  3150. Callback for Edit->Join. Joins the selected geometry objects into
  3151. a new one.
  3152. :return: None
  3153. """
  3154. self.defaults.report_usage("on_edit_join()")
  3155. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3156. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3157. geo_type_set = set()
  3158. objs = self.collection.get_selected()
  3159. if len(objs) < 2:
  3160. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3161. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3162. return 'fail'
  3163. for obj in objs:
  3164. geo_type_set.add(obj.multigeo)
  3165. # if len(geo_type_list) == 1 means that all list elements are the same
  3166. if len(geo_type_set) != 1:
  3167. self.inform.emit('[ERROR] %s' %
  3168. _("Failed join. The Geometry objects are of different types.\n"
  3169. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3170. "convert from one to another and retry joining \n"
  3171. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3172. "the result may not be what was expected. \n"
  3173. "Check the generated GCODE."))
  3174. return
  3175. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3176. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3177. if True in geo_type_set:
  3178. def initialize(geo_obj, app):
  3179. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3180. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3181. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3182. for v in geo_obj.tools.values():
  3183. v['data']['name'] = obj_name_multi
  3184. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3185. else:
  3186. def initialize(geo_obj, app):
  3187. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3188. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3189. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3190. for v in geo_obj.tools.values():
  3191. v['data']['name'] = obj_name_single
  3192. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3193. self.should_we_save = True
  3194. def on_edit_join_exc(self):
  3195. """
  3196. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3197. a new Excellon.
  3198. :return: None
  3199. """
  3200. self.defaults.report_usage("on_edit_join_exc()")
  3201. objs = self.collection.get_selected()
  3202. for obj in objs:
  3203. if not isinstance(obj, ExcellonObject):
  3204. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3205. return
  3206. if len(objs) < 2:
  3207. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3208. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3209. return 'fail'
  3210. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3211. def initialize(exc_obj, app):
  3212. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3213. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3214. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3215. self.should_we_save = True
  3216. def on_edit_join_grb(self):
  3217. """
  3218. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3219. a new Gerber object.
  3220. :return: None
  3221. """
  3222. self.defaults.report_usage("on_edit_join_grb()")
  3223. objs = self.collection.get_selected()
  3224. for obj in objs:
  3225. if not isinstance(obj, GerberObject):
  3226. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3227. return
  3228. if len(objs) < 2:
  3229. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3230. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3231. return 'fail'
  3232. def initialize(grb_obj, app):
  3233. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3234. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3235. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3236. self.should_we_save = True
  3237. def on_convert_singlegeo_to_multigeo(self):
  3238. """
  3239. Called for converting a Geometry object from single-geo to multi-geo.
  3240. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3241. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3242. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3243. the solid-geometry of that tool.
  3244. :return: None
  3245. """
  3246. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3247. obj = self.collection.get_active()
  3248. if obj is None:
  3249. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3250. return
  3251. if not isinstance(obj, GeometryObject):
  3252. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3253. return
  3254. obj.multigeo = True
  3255. for tooluid, dict_value in obj.tools.items():
  3256. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3257. if not isinstance(obj.solid_geometry, list):
  3258. obj.solid_geometry = [obj.solid_geometry]
  3259. # obj.solid_geometry[:] = []
  3260. obj.plot()
  3261. self.should_we_save = True
  3262. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3263. def on_convert_multigeo_to_singlegeo(self):
  3264. """
  3265. Called for converting a Geometry object from multi-geo to single-geo.
  3266. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3267. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3268. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3269. the solid-geometry of that tool.
  3270. :return: None
  3271. """
  3272. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3273. obj = self.collection.get_active()
  3274. if obj is None:
  3275. self.inform.emit('[ERROR_NOTCL] %s' %
  3276. _("Failed. Select a Geometry Object and try again."))
  3277. return
  3278. if not isinstance(obj, GeometryObject):
  3279. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3280. (_("Expected a GeometryObject, got"), type(obj)))
  3281. return
  3282. obj.multigeo = False
  3283. total_solid_geometry = []
  3284. for tooluid, dict_value in obj.tools.items():
  3285. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3286. # clear the original geometry
  3287. dict_value['solid_geometry'][:] = []
  3288. obj.solid_geometry = deepcopy(total_solid_geometry)
  3289. obj.plot()
  3290. self.should_we_save = True
  3291. self.inform.emit('[success] %s' %
  3292. _("A Geometry object was converted to SingleGeo type."))
  3293. def on_defaults_dict_change(self, field):
  3294. """
  3295. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3296. Edit -> Preferences tab window.
  3297. :param field: the key of the self.defaults dictionary that was changed.
  3298. :return: None
  3299. """
  3300. self.preferencesUiManager.defaults_write_form_field(field=field)
  3301. if field == "units":
  3302. self.set_screen_units(self.defaults['units'])
  3303. def set_screen_units(self, units):
  3304. """
  3305. Set the FlatCAM units on the status bar.
  3306. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3307. :return: None
  3308. """
  3309. self.ui.units_label.setText("[" + units.lower() + "]")
  3310. def on_toggle_units_click(self):
  3311. try:
  3312. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3313. except (TypeError, AttributeError):
  3314. pass
  3315. if self.defaults["units"] == 'MM':
  3316. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3317. else:
  3318. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3319. self.on_toggle_units(no_pref=True)
  3320. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3321. lambda: self.on_toggle_units(no_pref=False))
  3322. def on_toggle_units(self, no_pref=False):
  3323. """
  3324. Callback for the Units radio-button change in the Preferences tab.
  3325. Changes the application's default units adn for the project too.
  3326. If changing the project's units, the change propagates to all of
  3327. the objects in the project.
  3328. :return: None
  3329. """
  3330. self.defaults.report_usage("on_toggle_units")
  3331. if self.toggle_units_ignore:
  3332. return
  3333. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3334. # If option is the same, then ignore
  3335. if new_units == self.defaults["units"].upper():
  3336. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3337. return
  3338. # Keys in self.defaults for which to scale their values
  3339. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3340. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3341. "tools_iso_tool_vtipdia",
  3342. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3343. "gerber_editor_ma_high",
  3344. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3345. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3346. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3347. "excellon_feedrate_probe", "excellon_milling_dia",
  3348. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3349. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3350. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3351. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3352. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3353. "geometry_extracut_length", "geometry_z_pdepth",
  3354. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3355. 'cncjob_tooldia',
  3356. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3357. "tools_paintnewdia",
  3358. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3359. "tools_nccnewdia", "tools_ncc_offset_value",
  3360. "tools_2sided_drilldia",
  3361. "tools_film_boundary", "tools_film_scale_stroke",
  3362. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3363. "tools_cutout_depthperpass",
  3364. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3365. "tools_panelize_spacing_rows",
  3366. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3367. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3368. "tools_transform_buffer_dis",
  3369. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3370. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3371. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3372. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3373. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3374. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3375. "tools_cr_h2h_val", "tools_cr_dh_val",
  3376. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3377. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3378. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3379. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3380. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3381. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3382. "tools_copper_thieving_mask_clearance",
  3383. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3384. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3385. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3386. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3387. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3388. "tools_invert_margin",
  3389. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3390. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3391. def scale_defaults(sfactor):
  3392. for dim in dimensions:
  3393. if dim in [
  3394. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3395. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3396. 'tools_transform_mirror_point'
  3397. ]:
  3398. if self.defaults[dim] is None or self.defaults[dim] == '':
  3399. continue
  3400. try:
  3401. coordinates = self.defaults[dim].split(",")
  3402. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3403. coords_xy[0] *= sfactor
  3404. coords_xy[1] *= sfactor
  3405. self.defaults[dim] = "%.*f, %.*f" % (
  3406. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3407. except Exception as e:
  3408. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3409. elif dim in [
  3410. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3411. ]:
  3412. if self.defaults[dim] is None or self.defaults[dim] == '':
  3413. continue
  3414. try:
  3415. self.defaults[dim] = float(self.defaults[dim])
  3416. tools_diameters = [self.defaults[dim]]
  3417. except ValueError:
  3418. try:
  3419. tools_string = self.defaults[dim].split(",")
  3420. tools_diameters = [eval(a) for a in tools_string if a != '']
  3421. except Exception as e:
  3422. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3423. continue
  3424. self.defaults[dim] = ''
  3425. td_len = len(tools_diameters)
  3426. if td_len > 1:
  3427. for t in range(td_len):
  3428. tools_diameters[t] *= sfactor
  3429. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3430. else:
  3431. tools_diameters[0] *= sfactor
  3432. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3433. elif dim in ['global_gridx', 'global_gridy']:
  3434. # format the number of decimals to the one specified in self.decimals
  3435. try:
  3436. val = float(self.defaults[dim]) * sfactor
  3437. except Exception as e:
  3438. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3439. continue
  3440. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3441. else:
  3442. # the number of decimals for the rest is kept unchanged
  3443. if self.defaults[dim]:
  3444. try:
  3445. val = float(self.defaults[dim]) * sfactor
  3446. except Exception as e:
  3447. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3448. continue
  3449. self.defaults[dim] = val
  3450. # The scaling factor depending on choice of units.
  3451. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3452. # Changing project units. Warn user.
  3453. msgbox = QtWidgets.QMessageBox()
  3454. msgbox.setWindowTitle(_("Toggle Units"))
  3455. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3456. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3457. msgbox.setText(_("Changing the units of the project\n"
  3458. "will scale all objects.\n\n"
  3459. "Do you want to continue?"))
  3460. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3461. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3462. msgbox.setDefaultButton(bt_ok)
  3463. msgbox.exec_()
  3464. response = msgbox.clickedButton()
  3465. if response == bt_ok:
  3466. if no_pref is False:
  3467. self.preferencesUiManager.defaults_read_form()
  3468. scale_defaults(factor)
  3469. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3470. self.defaults["units"] = new_units
  3471. # update the defaults from form, some may assume that the conversion is enough and it's not
  3472. self.on_options_app2project()
  3473. # update the objects
  3474. for obj in self.collection.get_list():
  3475. obj.convert_units(new_units)
  3476. # make that the properties stored in the object are also updated
  3477. self.app_obj.object_changed.emit(obj)
  3478. # rebuild the object UI
  3479. obj.build_ui()
  3480. # change this only if the workspace is active
  3481. if self.defaults['global_workspace'] is True:
  3482. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3483. # adjust the grid values on the main toolbar
  3484. val_x = float(self.defaults['global_gridx']) * factor
  3485. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3486. current = self.collection.get_active()
  3487. if current is not None:
  3488. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3489. if not isinstance(current, GeometryObject):
  3490. current.to_form()
  3491. # replot all objects
  3492. self.plot_all()
  3493. # set the status labels to reflect the current FlatCAM units
  3494. self.set_screen_units(new_units)
  3495. # signal to the app that we changed the object properties and it should save the project
  3496. self.should_we_save = True
  3497. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3498. else:
  3499. # Undo toggling
  3500. self.toggle_units_ignore = True
  3501. if self.defaults['units'].upper() == 'MM':
  3502. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3503. else:
  3504. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3505. self.toggle_units_ignore = False
  3506. # store the grid values so they are not changed in the next step
  3507. val_x = float(self.defaults['global_gridx'])
  3508. val_y = float(self.defaults['global_gridy'])
  3509. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3510. self.preferencesUiManager.defaults_read_form()
  3511. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3512. # in self.defaults from the GUI elements but
  3513. # I don't want it for the grid values, so I update them here
  3514. self.defaults['global_gridx'] = val_x
  3515. self.defaults['global_gridy'] = val_y
  3516. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3517. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3518. def on_deselect_all(self):
  3519. self.collection.set_all_inactive()
  3520. self.delete_selection_shape()
  3521. def on_workspace_modified(self):
  3522. # self.save_defaults(silent=True)
  3523. self.plotcanvas.delete_workspace()
  3524. self.preferencesUiManager.defaults_read_form()
  3525. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3526. def on_workspace(self):
  3527. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3528. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3529. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3530. else:
  3531. self.plotcanvas.delete_workspace()
  3532. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3533. self.preferencesUiManager.defaults_read_form()
  3534. # self.save_defaults(silent=True)
  3535. def on_workspace_toggle(self):
  3536. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3537. try:
  3538. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3539. except TypeError:
  3540. pass
  3541. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3542. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3543. self.on_workspace()
  3544. def on_cursor_type(self, val):
  3545. """
  3546. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3547. :return: None
  3548. """
  3549. self.app_cursor.enabled = False
  3550. if val == 'small':
  3551. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3552. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3553. self.app_cursor = self.plotcanvas.new_cursor()
  3554. else:
  3555. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3556. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3557. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3558. if self.ui.grid_snap_btn.isChecked():
  3559. self.app_cursor.enabled = True
  3560. else:
  3561. self.app_cursor.enabled = False
  3562. def on_tool_add_keypress(self):
  3563. # ## Current application units in Upper Case
  3564. self.units = self.defaults['units'].upper()
  3565. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3566. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3567. if notebook_widget_name == 'selected_tab':
  3568. if self.collection.get_active().kind == 'geometry':
  3569. # Tool add works for Geometry only if Advanced is True in Preferences
  3570. if self.defaults["global_app_level"] == 'a':
  3571. tool_add_popup = FCInputDialog(title="New Tool ...",
  3572. text='Enter a Tool Diameter:',
  3573. min=0.0000, max=99.9999, decimals=4)
  3574. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3575. val, ok = tool_add_popup.get_value()
  3576. if ok:
  3577. if float(val) == 0:
  3578. self.inform.emit('[WARNING_NOTCL] %s' %
  3579. _("Please enter a tool diameter with non-zero value, in Float format."))
  3580. return
  3581. self.collection.get_active().on_tool_add(dia=float(val))
  3582. else:
  3583. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3584. else:
  3585. msgbox = QtWidgets.QMessageBox()
  3586. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3587. "Go to Preferences -> General - Show Advanced Options."))
  3588. msgbox.setWindowTitle("Tool adding ...")
  3589. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3590. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3591. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3592. msgbox.setDefaultButton(bt_ok)
  3593. msgbox.exec_()
  3594. # work only if the notebook tab on focus is the Tools_Tab
  3595. if notebook_widget_name == 'tool_tab':
  3596. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3597. # and only if the tool is NCC Tool
  3598. if tool_widget == self.ncclear_tool.toolName:
  3599. self.ncclear_tool.on_add_tool_by_key()
  3600. # and only if the tool is Paint Area Tool
  3601. elif tool_widget == self.paint_tool.toolName:
  3602. self.paint_tool.on_add_tool_by_key()
  3603. # and only if the tool is Solder Paste Dispensing Tool
  3604. elif tool_widget == self.paste_tool.toolName:
  3605. self.paste_tool.on_add_tool_by_key()
  3606. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3607. # See description below.
  3608. def on_delete_keypress(self):
  3609. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3610. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3611. if notebook_widget_name == 'selected_tab':
  3612. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3613. self.collection.get_active().on_tool_delete()
  3614. # work only if the notebook tab on focus is the Tools_Tab
  3615. elif notebook_widget_name == 'tool_tab':
  3616. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3617. # and only if the tool is NCC Tool
  3618. if tool_widget == self.ncclear_tool.toolName:
  3619. self.ncclear_tool.on_tool_delete()
  3620. # and only if the tool is Paint Tool
  3621. elif tool_widget == self.paint_tool.toolName:
  3622. self.paint_tool.on_tool_delete()
  3623. # and only if the tool is Solder Paste Dispensing Tool
  3624. elif tool_widget == self.paste_tool.toolName:
  3625. self.paste_tool.on_tool_delete()
  3626. # and only if the tool is Isolation Tool
  3627. elif tool_widget == self.isolation_tool.toolName:
  3628. self.isolation_tool.on_tool_delete()
  3629. else:
  3630. self.on_delete()
  3631. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3632. # some screens you have to be careful where you hover with your mouse.
  3633. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3634. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3635. # Complicated, I know :)
  3636. def on_delete(self, force_deletion=False):
  3637. """
  3638. Delete the currently selected FlatCAMObjs.
  3639. :param force_deletion: used by Tcl command
  3640. :return: None
  3641. """
  3642. self.defaults.report_usage("on_delete()")
  3643. response = None
  3644. bt_ok = None
  3645. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3646. # a geometry object before we update it.
  3647. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3648. and self.grb_editor.editor_active is False:
  3649. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3650. msgbox = QtWidgets.QMessageBox()
  3651. msgbox.setWindowTitle(_("Delete objects"))
  3652. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3653. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3654. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3655. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3656. "the selected objects?"))
  3657. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3658. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3659. msgbox.setDefaultButton(bt_ok)
  3660. msgbox.exec_()
  3661. response = msgbox.clickedButton()
  3662. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3663. response = bt_ok
  3664. if response == bt_ok:
  3665. if self.collection.get_active():
  3666. self.log.debug("App.on_delete()")
  3667. for obj_active in self.collection.get_selected():
  3668. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3669. if obj_active.kind == 'gerber':
  3670. obj_active.mark_shapes_storage.clear()
  3671. obj_active.mark_shapes.clear(update=True)
  3672. obj_active.mark_shapes.enabled = False
  3673. elif obj_active.kind == 'cncjob':
  3674. try:
  3675. obj_active.text_col.enabled = False
  3676. del obj_active.text_col
  3677. obj_active.annotation.clear(update=True)
  3678. del obj_active.annotation
  3679. except AttributeError as e:
  3680. log.debug(
  3681. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3682. )
  3683. while self.collection.get_selected():
  3684. self.delete_first_selected()
  3685. # make sure that the selection shape is deleted, too
  3686. self.delete_selection_shape()
  3687. # if there are no longer objects delete also the exclusion areas shapes
  3688. if not self.collection.get_list():
  3689. self.exc_areas.clear_shapes()
  3690. self.inform.emit('%s...' % _("Object(s) deleted"))
  3691. else:
  3692. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3693. else:
  3694. self.inform.emit(_("Save the work in Editor and try again ..."))
  3695. def delete_first_selected(self):
  3696. # Keep this for later
  3697. try:
  3698. sel_obj = self.collection.get_active()
  3699. name = sel_obj.options["name"]
  3700. isPlotted = sel_obj.options["plot"]
  3701. except AttributeError:
  3702. self.log.debug("Nothing selected for deletion")
  3703. return
  3704. if self.is_legacy is True:
  3705. # Remove plot only if the object was plotted otherwise delaxes will fail
  3706. if isPlotted:
  3707. try:
  3708. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3709. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3710. except Exception as e:
  3711. log.debug("App.delete_first_selected() --> %s" % str(e))
  3712. self.plotcanvas.auto_adjust_axes()
  3713. # Remove from dictionary
  3714. self.collection.delete_active()
  3715. # Clear form
  3716. self.setup_component_editor()
  3717. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3718. def on_set_origin(self):
  3719. """
  3720. Set the origin to the left mouse click position
  3721. :return: None
  3722. """
  3723. # display the message for the user
  3724. # and ask him to click on the desired position
  3725. self.defaults.report_usage("on_set_origin()")
  3726. def origin_replot():
  3727. def worker_task():
  3728. with self.proc_container.new('%s...' % _("Plotting")):
  3729. for obj in self.collection.get_list():
  3730. obj.plot()
  3731. self.plotcanvas.fit_view()
  3732. if self.is_legacy:
  3733. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3734. else:
  3735. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3736. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3737. self.inform.emit(_('Click to set the origin ...'))
  3738. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3739. # first disconnect it as it may have been used by something else
  3740. try:
  3741. self.replot_signal.disconnect()
  3742. except TypeError:
  3743. pass
  3744. self.replot_signal[list].connect(origin_replot)
  3745. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3746. """
  3747. :param event:
  3748. :param location:
  3749. :param noplot:
  3750. :param use_thread:
  3751. :return:
  3752. """
  3753. noplot_sig = noplot
  3754. def worker_task():
  3755. with self.proc_container.new(_("Setting Origin...")):
  3756. obj_list = self.collection.get_list()
  3757. for obj in obj_list:
  3758. obj.offset((x, y))
  3759. self.app_obj.object_changed.emit(obj)
  3760. # Update the object bounding box options
  3761. a, b, c, d = obj.bounds()
  3762. obj.options['xmin'] = a
  3763. obj.options['ymin'] = b
  3764. obj.options['xmax'] = c
  3765. obj.options['ymax'] = d
  3766. self.inform.emit('[success] %s...' % _('Origin set'))
  3767. for obj in obj_list:
  3768. out_name = obj.options["name"]
  3769. if obj.kind == 'gerber':
  3770. obj.source_file = self.export_gerber(
  3771. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3772. elif obj.kind == 'excellon':
  3773. obj.source_file = self.export_excellon(
  3774. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3775. if noplot_sig is False:
  3776. self.replot_signal.emit([])
  3777. if location is not None:
  3778. if len(location) != 2:
  3779. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3780. return 'fail'
  3781. x, y = location
  3782. if use_thread is True:
  3783. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3784. else:
  3785. worker_task()
  3786. self.should_we_save = True
  3787. return
  3788. if event is not None and event.button == 1:
  3789. if self.is_legacy is False:
  3790. event_pos = event.pos
  3791. else:
  3792. event_pos = (event.xdata, event.ydata)
  3793. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3794. if self.grid_status():
  3795. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3796. else:
  3797. pos = pos_canvas
  3798. x = 0 - pos[0]
  3799. y = 0 - pos[1]
  3800. if use_thread is True:
  3801. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3802. else:
  3803. worker_task()
  3804. self.should_we_save = True
  3805. def on_move2origin(self, use_thread=True):
  3806. """
  3807. Move selected objects to origin.
  3808. :param use_thread: Control if to use threaded operation. Boolean.
  3809. :return:
  3810. """
  3811. def worker_task():
  3812. with self.proc_container.new(_("Moving to Origin...")):
  3813. obj_list = self.collection.get_selected()
  3814. if not obj_list:
  3815. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3816. return
  3817. xminlist = []
  3818. yminlist = []
  3819. # first get a bounding box to fit all
  3820. for obj in obj_list:
  3821. xmin, ymin, xmax, ymax = obj.bounds()
  3822. xminlist.append(xmin)
  3823. yminlist.append(ymin)
  3824. # get the minimum x,y for all objects selected
  3825. x = min(xminlist)
  3826. y = min(yminlist)
  3827. for obj in obj_list:
  3828. obj.offset((-x, -y))
  3829. self.app_obj.object_changed.emit(obj)
  3830. # Update the object bounding box options
  3831. a, b, c, d = obj.bounds()
  3832. obj.options['xmin'] = a
  3833. obj.options['ymin'] = b
  3834. obj.options['xmax'] = c
  3835. obj.options['ymax'] = d
  3836. for obj in obj_list:
  3837. obj.plot()
  3838. for obj in obj_list:
  3839. out_name = obj.options["name"]
  3840. if obj.kind == 'gerber':
  3841. obj.source_file = self.export_gerber(
  3842. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3843. elif obj.kind == 'excellon':
  3844. obj.source_file = self.export_excellon(
  3845. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3846. self.inform.emit('[success] %s...' % _('Origin set'))
  3847. if use_thread is True:
  3848. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3849. else:
  3850. worker_task()
  3851. self.should_we_save = True
  3852. def on_jump_to(self, custom_location=None, fit_center=True):
  3853. """
  3854. Jump to a location by setting the mouse cursor location.
  3855. :param custom_location: Jump to a specified point. (x, y) tuple.
  3856. :param fit_center: If to fit view. Boolean.
  3857. :return:
  3858. """
  3859. self.defaults.report_usage("on_jump_to()")
  3860. if not custom_location:
  3861. dia_box_location = None
  3862. try:
  3863. dia_box_location = eval(self.clipboard.text())
  3864. except Exception:
  3865. pass
  3866. if type(dia_box_location) == tuple:
  3867. dia_box_location = str(dia_box_location)
  3868. else:
  3869. dia_box_location = None
  3870. # dia_box = Dialog_box(title=_("Jump to ..."),
  3871. # label=_("Enter the coordinates in format X,Y:"),
  3872. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3873. # initial_text=dia_box_location)
  3874. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3875. label=_("Enter the coordinates in format X,Y:"),
  3876. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3877. initial_text=dia_box_location,
  3878. reference=self.defaults['global_jump_ref'])
  3879. if dia_box.ok is True:
  3880. try:
  3881. location = eval(dia_box.location)
  3882. if not isinstance(location, tuple):
  3883. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3884. return
  3885. if dia_box.reference == 'rel':
  3886. rel_x = self.mouse[0] + location[0]
  3887. rel_y = self.mouse[1] + location[1]
  3888. location = (rel_x, rel_y)
  3889. self.defaults['global_jump_ref'] = dia_box.reference
  3890. except Exception:
  3891. return
  3892. else:
  3893. return
  3894. else:
  3895. location = custom_location
  3896. self.jump_signal.emit(location)
  3897. if fit_center:
  3898. self.plotcanvas.fit_center(loc=location)
  3899. cursor = QtGui.QCursor()
  3900. if self.is_legacy is False:
  3901. # I don't know where those differences come from but they are constant for the current
  3902. # execution of the application and they are multiples of a value around 0.0263mm.
  3903. # In a random way sometimes they are more sometimes they are less
  3904. # if units == 'MM':
  3905. # cal_factor = 0.0263
  3906. # else:
  3907. # cal_factor = 0.0263 / 25.4
  3908. cal_location = (location[0], location[1])
  3909. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3910. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3911. j_pos = (
  3912. int(canvas_origin.x() + round(jump_loc[0])),
  3913. int(canvas_origin.y() + round(jump_loc[1]))
  3914. )
  3915. cursor.setPos(j_pos[0], j_pos[1])
  3916. else:
  3917. # find the canvas origin which is in the top left corner
  3918. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3919. # determine the coordinates for the lowest left point of the canvas
  3920. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3921. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3922. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3923. # canvas) and the point (width, height) is in the top-right location
  3924. loc = self.plotcanvas.axes.transData.transform_point(location)
  3925. j_pos = (
  3926. int(x0 + loc[0]),
  3927. int(y0 - loc[1])
  3928. )
  3929. cursor.setPos(j_pos[0], j_pos[1])
  3930. self.plotcanvas.mouse = [location[0], location[1]]
  3931. if self.defaults["global_cursor_color_enabled"] is True:
  3932. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3933. else:
  3934. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3935. if self.grid_status():
  3936. # Update cursor
  3937. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3938. symbol='++', edge_color=self.cursor_color_3D,
  3939. edge_width=self.defaults["global_cursor_width"],
  3940. size=self.defaults["global_cursor_size"])
  3941. # Set the relative position label
  3942. dx = location[0] - float(self.rel_point1[0])
  3943. dy = location[1] - float(self.rel_point1[1])
  3944. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3945. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3946. # Set the position label
  3947. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3948. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3949. units = self.defaults["units"].lower()
  3950. self.plotcanvas.text_hud.text = \
  3951. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3952. dx, units, dy, units, location[0], units, location[1], units)
  3953. self.inform.emit('[success] %s' % _("Done."))
  3954. return location
  3955. def on_locate(self, obj, fit_center=True):
  3956. """
  3957. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3958. :param obj: The object on which to locate certain points
  3959. :param fit_center: If to fit view. Boolean.
  3960. :return: A point location. (x, y) tuple.
  3961. """
  3962. self.defaults.report_usage("on_locate()")
  3963. if obj is None:
  3964. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3965. return 'fail'
  3966. class DialogBoxChoice(QtWidgets.QDialog):
  3967. def __init__(self, title=None, icon=None, choice='bl'):
  3968. """
  3969. :param title: string with the window title
  3970. """
  3971. super(DialogBoxChoice, self).__init__()
  3972. self.ok = False
  3973. self.setWindowIcon(icon)
  3974. self.setWindowTitle(str(title))
  3975. self.form = QtWidgets.QFormLayout(self)
  3976. self.ref_radio = RadioSet([
  3977. {"label": _("Bottom-Left"), "value": "bl"},
  3978. {"label": _("Top-Left"), "value": "tl"},
  3979. {"label": _("Bottom-Right"), "value": "br"},
  3980. {"label": _("Top-Right"), "value": "tr"},
  3981. {"label": _("Center"), "value": "c"}
  3982. ], orientation='vertical', stretch=False)
  3983. self.ref_radio.set_value(choice)
  3984. self.form.addRow(self.ref_radio)
  3985. self.button_box = QtWidgets.QDialogButtonBox(
  3986. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3987. Qt.Horizontal, parent=self)
  3988. self.form.addRow(self.button_box)
  3989. self.button_box.accepted.connect(self.accept)
  3990. self.button_box.rejected.connect(self.reject)
  3991. if self.exec_() == QtWidgets.QDialog.Accepted:
  3992. self.ok = True
  3993. self.location_point = self.ref_radio.get_value()
  3994. else:
  3995. self.ok = False
  3996. self.location_point = None
  3997. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3998. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3999. choice=self.defaults['global_locate_pt'])
  4000. if dia_box.ok is True:
  4001. try:
  4002. location_point = dia_box.location_point
  4003. self.defaults['global_locate_pt'] = dia_box.location_point
  4004. except Exception:
  4005. return
  4006. else:
  4007. return
  4008. loc_b = obj.bounds()
  4009. if location_point == 'bl':
  4010. location = (loc_b[0], loc_b[1])
  4011. elif location_point == 'tl':
  4012. location = (loc_b[0], loc_b[3])
  4013. elif location_point == 'br':
  4014. location = (loc_b[2], loc_b[1])
  4015. elif location_point == 'tr':
  4016. location = (loc_b[2], loc_b[3])
  4017. else:
  4018. # center
  4019. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4020. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4021. location = (cx, cy)
  4022. self.locate_signal.emit(location, location_point)
  4023. if fit_center:
  4024. self.plotcanvas.fit_center(loc=location)
  4025. cursor = QtGui.QCursor()
  4026. if self.is_legacy is False:
  4027. # I don't know where those differences come from but they are constant for the current
  4028. # execution of the application and they are multiples of a value around 0.0263mm.
  4029. # In a random way sometimes they are more sometimes they are less
  4030. # if units == 'MM':
  4031. # cal_factor = 0.0263
  4032. # else:
  4033. # cal_factor = 0.0263 / 25.4
  4034. cal_location = (location[0], location[1])
  4035. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4036. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4037. j_pos = (
  4038. int(canvas_origin.x() + round(jump_loc[0])),
  4039. int(canvas_origin.y() + round(jump_loc[1]))
  4040. )
  4041. cursor.setPos(j_pos[0], j_pos[1])
  4042. else:
  4043. # find the canvas origin which is in the top left corner
  4044. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4045. # determine the coordinates for the lowest left point of the canvas
  4046. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4047. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4048. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4049. # canvas) and the point (width, height) is in the top-right location
  4050. loc = self.plotcanvas.axes.transData.transform_point(location)
  4051. j_pos = (
  4052. int(x0 + loc[0]),
  4053. int(y0 - loc[1])
  4054. )
  4055. cursor.setPos(j_pos[0], j_pos[1])
  4056. self.plotcanvas.mouse = [location[0], location[1]]
  4057. if self.defaults["global_cursor_color_enabled"] is True:
  4058. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4059. else:
  4060. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4061. if self.grid_status():
  4062. # Update cursor
  4063. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4064. symbol='++', edge_color=self.cursor_color_3D,
  4065. edge_width=self.defaults["global_cursor_width"],
  4066. size=self.defaults["global_cursor_size"])
  4067. # Set the relative position label
  4068. self.dx = location[0] - float(self.rel_point1[0])
  4069. self.dy = location[1] - float(self.rel_point1[1])
  4070. # Set the position label
  4071. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4072. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4073. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4074. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4075. units = self.defaults["units"].lower()
  4076. self.plotcanvas.text_hud.text = \
  4077. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4078. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4079. self.inform.emit('[success] %s' % _("Done."))
  4080. return location
  4081. def on_copy_command(self):
  4082. """
  4083. Will copy a selection of objects, creating new objects.
  4084. :return:
  4085. """
  4086. self.defaults.report_usage("on_copy_command()")
  4087. def initialize(obj_init, app):
  4088. """
  4089. :param obj_init: the new object
  4090. :type obj_init: class
  4091. :param app: An instance of the App class
  4092. :type app: App
  4093. :return: None
  4094. :rtype:
  4095. """
  4096. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4097. try:
  4098. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4099. except AttributeError:
  4100. pass
  4101. try:
  4102. obj_init.apertures = deepcopy(obj.apertures)
  4103. except AttributeError:
  4104. pass
  4105. try:
  4106. if obj.tools:
  4107. obj_init.tools = deepcopy(obj.tools)
  4108. except Exception as err:
  4109. log.debug("App.on_copy_command() --> %s" % str(err))
  4110. try:
  4111. obj_init.source_file = deepcopy(obj.source_file)
  4112. except (AttributeError, TypeError):
  4113. pass
  4114. def initialize_excellon(obj_init, app):
  4115. obj_init.source_file = deepcopy(obj.source_file)
  4116. obj_init.tools = deepcopy(obj.tools)
  4117. # drills are offset, so they need to be deep copied
  4118. obj_init.drills = deepcopy(obj.drills)
  4119. # slots are offset, so they need to be deep copied
  4120. obj_init.slots = deepcopy(obj.slots)
  4121. obj_init.create_geometry()
  4122. def initialize_script(obj_init, app_obj):
  4123. obj_init.source_file = deepcopy(obj.source_file)
  4124. def initialize_document(obj_init, app_obj):
  4125. obj_init.source_file = deepcopy(obj.source_file)
  4126. for obj in self.collection.get_selected():
  4127. obj_name = obj.options["name"]
  4128. try:
  4129. if isinstance(obj, ExcellonObject):
  4130. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4131. elif isinstance(obj, GerberObject):
  4132. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4133. elif isinstance(obj, GeometryObject):
  4134. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4135. elif isinstance(obj, ScriptObject):
  4136. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4137. elif isinstance(obj, DocumentObject):
  4138. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4139. except Exception as e:
  4140. return "Operation failed: %s" % str(e)
  4141. def on_copy_object2(self, custom_name):
  4142. def initialize_geometry(obj_init, app):
  4143. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4144. try:
  4145. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4146. except AttributeError:
  4147. pass
  4148. try:
  4149. obj_init.apertures = deepcopy(obj.apertures)
  4150. except AttributeError:
  4151. pass
  4152. try:
  4153. if obj.tools:
  4154. obj_init.tools = deepcopy(obj.tools)
  4155. except Exception as ee:
  4156. log.debug("on_copy_object2() --> %s" % str(ee))
  4157. def initialize_gerber(obj_init, app):
  4158. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4159. obj_init.apertures = deepcopy(obj.apertures)
  4160. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4161. def initialize_excellon(obj_init, app):
  4162. obj_init.tools = deepcopy(obj.tools)
  4163. # drills are offset, so they need to be deep copied
  4164. obj_init.drills = deepcopy(obj.drills)
  4165. # slots are offset, so they need to be deep copied
  4166. obj_init.slots = deepcopy(obj.slots)
  4167. obj_init.create_geometry()
  4168. for obj in self.collection.get_selected():
  4169. obj_name = obj.options["name"]
  4170. try:
  4171. if isinstance(obj, ExcellonObject):
  4172. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4173. elif isinstance(obj, GerberObject):
  4174. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4175. elif isinstance(obj, GeometryObject):
  4176. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4177. except Exception as er:
  4178. return "Operation failed: %s" % str(er)
  4179. def on_rename_object(self, text):
  4180. """
  4181. Will rename an object.
  4182. :param text: New name for the object.
  4183. :return:
  4184. """
  4185. self.defaults.report_usage("on_rename_object()")
  4186. named_obj = self.collection.get_active()
  4187. for obj in named_obj:
  4188. if obj is list:
  4189. self.on_rename_object(text)
  4190. else:
  4191. try:
  4192. obj.options['name'] = text
  4193. except Exception as e:
  4194. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4195. def convert_any2geo(self):
  4196. """
  4197. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4198. :return:
  4199. """
  4200. self.defaults.report_usage("convert_any2geo()")
  4201. def initialize(obj_init, app):
  4202. obj_init.solid_geometry = obj.solid_geometry
  4203. try:
  4204. obj_init.follow_geometry = obj.follow_geometry
  4205. except AttributeError:
  4206. pass
  4207. try:
  4208. obj_init.apertures = obj.apertures
  4209. except AttributeError:
  4210. pass
  4211. try:
  4212. if obj.tools:
  4213. obj_init.tools = obj.tools
  4214. except AttributeError:
  4215. pass
  4216. def initialize_excellon(obj_init, app):
  4217. # objs = self.collection.get_selected()
  4218. # GeometryObject.merge(objs, obj)
  4219. solid_geo = []
  4220. for tool in obj.tools:
  4221. for geo in obj.tools[tool]['solid_geometry']:
  4222. solid_geo.append(geo)
  4223. obj_init.solid_geometry = deepcopy(solid_geo)
  4224. if not self.collection.get_selected():
  4225. log.warning("App.convert_any2geo --> No object selected")
  4226. self.inform.emit('[WARNING_NOTCL] %s' %
  4227. _("No object is selected. Select an object and try again."))
  4228. return
  4229. for obj in self.collection.get_selected():
  4230. obj_name = obj.options["name"]
  4231. try:
  4232. if obj.kind == 'excellon':
  4233. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4234. else:
  4235. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4236. except Exception as e:
  4237. return "Operation failed: %s" % str(e)
  4238. def convert_any2gerber(self):
  4239. """
  4240. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4241. :return:
  4242. """
  4243. def initialize_geometry(obj_init, app):
  4244. apertures = {}
  4245. apid = 0
  4246. apertures[str(apid)] = {}
  4247. apertures[str(apid)]['geometry'] = []
  4248. for obj_orig in obj.solid_geometry:
  4249. new_elem = {}
  4250. new_elem['solid'] = obj_orig
  4251. try:
  4252. new_elem['follow'] = obj_orig.exterior
  4253. except AttributeError:
  4254. pass
  4255. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4256. apertures[str(apid)]['size'] = 0.0
  4257. apertures[str(apid)]['type'] = 'C'
  4258. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4259. obj_init.apertures = deepcopy(apertures)
  4260. def initialize_excellon(obj_init, app):
  4261. apertures = {}
  4262. apid = 10
  4263. for tool in obj.tools:
  4264. apertures[str(apid)] = {}
  4265. apertures[str(apid)]['geometry'] = []
  4266. for geo in obj.tools[tool]['solid_geometry']:
  4267. new_el = {}
  4268. new_el['solid'] = geo
  4269. new_el['follow'] = geo.exterior
  4270. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4271. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4272. apertures[str(apid)]['type'] = 'C'
  4273. apid += 1
  4274. # create solid_geometry
  4275. solid_geometry = []
  4276. for apid in apertures:
  4277. for geo_el in apertures[apid]['geometry']:
  4278. solid_geometry.append(geo_el['solid'])
  4279. solid_geometry = MultiPolygon(solid_geometry)
  4280. solid_geometry = solid_geometry.buffer(0.0000001)
  4281. obj_init.solid_geometry = deepcopy(solid_geometry)
  4282. obj_init.apertures = deepcopy(apertures)
  4283. # clear the working objects (perhaps not necessary due of Python GC)
  4284. apertures.clear()
  4285. if not self.collection.get_selected():
  4286. log.warning("App.convert_any2gerber --> No object selected")
  4287. self.inform.emit('[WARNING_NOTCL] %s' %
  4288. _("No object is selected. Select an object and try again."))
  4289. return
  4290. for obj in self.collection.get_selected():
  4291. obj_name = obj.options["name"]
  4292. try:
  4293. if obj.kind == 'excellon':
  4294. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4295. elif obj.kind == 'geometry':
  4296. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4297. else:
  4298. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4299. except Exception as e:
  4300. return "Operation failed: %s" % str(e)
  4301. def convert_any2excellon(self):
  4302. """
  4303. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4304. :return:
  4305. """
  4306. def initialize_geometry(obj_init, app):
  4307. tools = {}
  4308. tooluid = 1
  4309. obj_init.solid_geometry = []
  4310. for geo in obj.solid_geometry:
  4311. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4312. continue
  4313. minx, miny, maxx, maxy = geo.bounds
  4314. new_dia = min([maxx-minx, maxy-miny])
  4315. new_drill = geo.centroid
  4316. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4317. current_tooldias = []
  4318. if tools:
  4319. for tool in tools:
  4320. if tools[tool] and 'tooldia' in tools[tool]:
  4321. current_tooldias.append(tools[tool]['tooldia'])
  4322. if new_dia in current_tooldias:
  4323. for tool in tools:
  4324. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float('%.*f' % (self.decimals,
  4325. new_dia)):
  4326. tools[tool]['drills'].append(new_drill)
  4327. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4328. else:
  4329. tools[tooluid] = {}
  4330. tools[tooluid]['tooldia'] = new_dia
  4331. tools[tooluid]['drills'] = [new_drill]
  4332. tools[tooluid]['slots'] = []
  4333. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4334. tooluid += 1
  4335. try:
  4336. obj_init.solid_geometry.append(new_drill_geo)
  4337. except (TypeError, AttributeError):
  4338. obj_init.solid_geometry = [new_drill_geo]
  4339. obj_init.tools = deepcopy(tools)
  4340. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4341. def initialize_gerber(obj_init, app):
  4342. tools = {}
  4343. tooluid = 1
  4344. obj_init.solid_geometry = []
  4345. for apid in obj.apertures:
  4346. if 'geometry' in obj.apertures[apid]:
  4347. for geo_dict in obj.apertures[apid]['geometry']:
  4348. if 'follow' in geo_dict:
  4349. if isinstance(geo_dict['follow'], Point):
  4350. geo = geo_dict['solid']
  4351. minx, miny, maxx, maxy = geo.bounds
  4352. new_dia = min([maxx - minx, maxy - miny])
  4353. new_drill = geo.centroid
  4354. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4355. current_tooldias = []
  4356. if tools:
  4357. for tool in tools:
  4358. if tools[tool] and 'tooldia' in tools[tool]:
  4359. current_tooldias.append(
  4360. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4361. )
  4362. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4363. for tool in tools:
  4364. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4365. '%.*f' % (self.decimals, new_dia)):
  4366. if new_drill not in tools[tool]['drills']:
  4367. tools[tool]['drills'].append(new_drill)
  4368. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4369. else:
  4370. tools[tooluid] = {}
  4371. tools[tooluid]['tooldia'] = new_dia
  4372. tools[tooluid]['drills'] = [new_drill]
  4373. tools[tooluid]['slots'] = []
  4374. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4375. tooluid += 1
  4376. try:
  4377. obj_init.solid_geometry.append(new_drill_geo)
  4378. except (TypeError, AttributeError):
  4379. obj_init.solid_geometry = [new_drill_geo]
  4380. elif isinstance(geo_dict['follow'], LineString):
  4381. geo_coords = list(geo_dict['follow'].coords)
  4382. # slots can have only a start and stop point and no intermediate points
  4383. if len(geo_coords) != 2:
  4384. continue
  4385. geo = geo_dict['solid']
  4386. try:
  4387. new_dia = obj.apertures[apid]['size']
  4388. except Exception:
  4389. continue
  4390. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4391. new_slot_geo = geo
  4392. current_tooldias = []
  4393. if tools:
  4394. for tool in tools:
  4395. if tools[tool] and 'tooldia' in tools[tool]:
  4396. current_tooldias.append(
  4397. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4398. )
  4399. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4400. for tool in tools:
  4401. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4402. '%.*f' % (self.decimals, new_dia)):
  4403. if new_slot not in tools[tool]['slots']:
  4404. tools[tool]['slots'].append(new_slot)
  4405. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4406. else:
  4407. tools[tooluid] = {}
  4408. tools[tooluid]['tooldia'] = new_dia
  4409. tools[tooluid]['drills'] = []
  4410. tools[tooluid]['slots'] = [new_slot]
  4411. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4412. tooluid += 1
  4413. try:
  4414. obj_init.solid_geometry.append(new_slot_geo)
  4415. except (TypeError, AttributeError):
  4416. obj_init.solid_geometry = [new_slot_geo]
  4417. obj_init.tools = deepcopy(tools)
  4418. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4419. if not self.collection.get_selected():
  4420. log.warning("App.convert_any2excellon--> No object selected")
  4421. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4422. return
  4423. for obj in self.collection.get_selected():
  4424. obj_name = obj.options["name"]
  4425. try:
  4426. if obj.kind == 'gerber':
  4427. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4428. elif obj.kind == 'geometry':
  4429. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4430. else:
  4431. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4432. except Exception as e:
  4433. return "Operation failed: %s" % str(e)
  4434. def abort_all_tasks(self):
  4435. """
  4436. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4437. on the first possible occasion.
  4438. :return:
  4439. """
  4440. if self.abort_flag is False:
  4441. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4442. self.abort_flag = True
  4443. self.cleanup.emit()
  4444. def app_is_idle(self):
  4445. if self.abort_flag:
  4446. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4447. self.abort_flag = False
  4448. def on_selectall(self):
  4449. """
  4450. Will draw a selection box shape around the selected objects.
  4451. :return:
  4452. """
  4453. self.defaults.report_usage("on_selectall()")
  4454. # delete the possible selection box around a possible selected object
  4455. self.delete_selection_shape()
  4456. for name in self.collection.get_names():
  4457. self.collection.set_active(name)
  4458. curr_sel_obj = self.collection.get_by_name(name)
  4459. # create the selection box around the selected object
  4460. if self.defaults['global_selection_shape'] is True:
  4461. self.draw_selection_shape(curr_sel_obj)
  4462. def on_toggle_preferences(self):
  4463. pref_open = False
  4464. for idx in range(self.ui.plot_tab_area.count()):
  4465. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4466. pref_open = True
  4467. if pref_open:
  4468. for idx in range(self.ui.plot_tab_area.count()):
  4469. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4470. self.ui.plot_tab_area.removeTab(idx)
  4471. break
  4472. self.ui.pref_status_label.setStyleSheet("")
  4473. else:
  4474. self.on_preferences()
  4475. def on_preferences(self):
  4476. """
  4477. Adds the Preferences in a Tab in Plot Area
  4478. :return:
  4479. """
  4480. # add the tab if it was closed
  4481. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4482. # delete the absolute and relative position and messages in the infobar
  4483. # self.ui.position_label.setText("")
  4484. # self.ui.rel_position_label.setText("")
  4485. # hide coordinates toolbars in the infobar while in DB
  4486. self.ui.coords_toolbar.hide()
  4487. self.ui.delta_coords_toolbar.hide()
  4488. # Switch plot_area to preferences page
  4489. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4490. # self.ui.show()
  4491. self.ui.pref_status_label.setStyleSheet("""
  4492. QLabel
  4493. {
  4494. color: black;
  4495. background-color: lightseagreen;
  4496. }
  4497. """
  4498. )
  4499. # detect changes in the preferences
  4500. for idx in range(self.ui.pref_tab_area.count()):
  4501. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4502. try:
  4503. try:
  4504. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4505. except (TypeError, AttributeError):
  4506. pass
  4507. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4508. except AttributeError:
  4509. pass
  4510. try:
  4511. try:
  4512. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4513. except (TypeError, AttributeError):
  4514. pass
  4515. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4516. except AttributeError:
  4517. pass
  4518. try:
  4519. try:
  4520. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4521. except (TypeError, AttributeError):
  4522. pass
  4523. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4524. except AttributeError:
  4525. pass
  4526. try:
  4527. try:
  4528. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4529. except (TypeError, AttributeError):
  4530. pass
  4531. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4532. except AttributeError:
  4533. pass
  4534. try:
  4535. try:
  4536. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4537. except (TypeError, AttributeError):
  4538. pass
  4539. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4540. except AttributeError:
  4541. pass
  4542. def on_tools_database(self, source='app'):
  4543. """
  4544. Adds the Tools Database in a Tab in Plot Area.
  4545. :return:
  4546. """
  4547. for idx in range(self.ui.plot_tab_area.count()):
  4548. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4549. # there can be only one instance of Tools Database at one time
  4550. return
  4551. if source == 'app':
  4552. self.tools_db_tab = ToolsDB2(
  4553. app=self,
  4554. parent=self.ui,
  4555. callback_on_edited=self.on_tools_db_edited,
  4556. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4557. )
  4558. elif source == 'ncc':
  4559. self.tools_db_tab = ToolsDB2(
  4560. app=self,
  4561. parent=self.ui,
  4562. callback_on_edited=self.on_tools_db_edited,
  4563. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4564. )
  4565. elif source == 'paint':
  4566. self.tools_db_tab = ToolsDB2(
  4567. app=self,
  4568. parent=self.ui,
  4569. callback_on_edited=self.on_tools_db_edited,
  4570. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4571. )
  4572. elif source == 'iso':
  4573. self.tools_db_tab = ToolsDB2(
  4574. app=self,
  4575. parent=self.ui,
  4576. callback_on_edited=self.on_tools_db_edited,
  4577. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4578. )
  4579. # add the tab if it was closed
  4580. try:
  4581. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4582. self.tools_db_tab.setObjectName("database_tab")
  4583. except Exception as e:
  4584. log.debug("App.on_tools_database() --> %s" % str(e))
  4585. return
  4586. # delete the absolute and relative position and messages in the infobar
  4587. # self.ui.position_label.setText("")
  4588. # self.ui.rel_position_label.setText("")
  4589. # hide coordinates toolbars in the infobar while in DB
  4590. self.ui.coords_toolbar.hide()
  4591. self.ui.delta_coords_toolbar.hide()
  4592. # Switch plot_area to preferences page
  4593. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4594. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4595. self.tools_db_tab.ui_connect()
  4596. def on_tools_db_edited(self):
  4597. """
  4598. Executed whenever a tool is edited in Tools Database.
  4599. Will color the text of the Tools Database tab to Red color.
  4600. :return:
  4601. """
  4602. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4603. for idx in range(self.ui.plot_tab_area.count()):
  4604. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4605. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4606. self.tools_db_tab.ui.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4607. self.tools_db_changed_flag = True
  4608. def on_geometry_tool_add_from_db_executed(self, tool):
  4609. """
  4610. Here add the tool from DB in the selected geometry object.
  4611. :return:
  4612. """
  4613. tool_from_db = deepcopy(tool)
  4614. obj = self.collection.get_active()
  4615. if obj.kind == 'geometry':
  4616. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4617. # close the tab and delete it
  4618. for idx in range(self.ui.plot_tab_area.count()):
  4619. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4620. wdg = self.ui.plot_tab_area.widget(idx)
  4621. wdg.deleteLater()
  4622. self.ui.plot_tab_area.removeTab(idx)
  4623. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4624. elif obj.kind == 'gerber':
  4625. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4626. # close the tab and delete it
  4627. for idx in range(self.ui.plot_tab_area.count()):
  4628. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4629. wdg = self.ui.plot_tab_area.widget(idx)
  4630. wdg.deleteLater()
  4631. self.ui.plot_tab_area.removeTab(idx)
  4632. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4633. else:
  4634. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4635. def on_plot_area_tab_closed(self, tab_obj_name):
  4636. """
  4637. Executed whenever a QTab is closed in the Plot Area.
  4638. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4639. :return:
  4640. """
  4641. if tab_obj_name == "preferences_tab":
  4642. self.preferencesUiManager.on_close_preferences_tab()
  4643. elif tab_obj_name == "database_tab":
  4644. # disconnect the signals from the table widget in tab
  4645. self.tools_db_tab.ui_disconnect()
  4646. if self.tools_db_changed_flag is True:
  4647. msgbox = QtWidgets.QMessageBox()
  4648. msgbox.setText(_("One or more Tools are edited.\n"
  4649. "Do you want to update the Tools Database?"))
  4650. msgbox.setWindowTitle(_("Save Tools Database"))
  4651. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4652. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4653. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4654. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4655. msgbox.setDefaultButton(bt_yes)
  4656. msgbox.exec_()
  4657. response = msgbox.clickedButton()
  4658. if response == bt_yes:
  4659. self.tools_db_tab.on_save_tools_db()
  4660. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4661. else:
  4662. self.tools_db_changed_flag = False
  4663. self.inform.emit('')
  4664. return
  4665. self.tools_db_tab.deleteLater()
  4666. elif tab_obj_name == "text_editor_tab":
  4667. self.toggle_codeeditor = False
  4668. elif tab_obj_name == "bookmarks_tab":
  4669. self.book_dialog_tab.rebuild_actions()
  4670. self.book_dialog_tab.deleteLater()
  4671. else:
  4672. pass
  4673. # restore the coords toolbars
  4674. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4675. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4676. def on_flipy(self):
  4677. """
  4678. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4679. :return:
  4680. """
  4681. self.defaults.report_usage("on_flipy()")
  4682. obj_list = self.collection.get_selected()
  4683. xminlist = []
  4684. yminlist = []
  4685. xmaxlist = []
  4686. ymaxlist = []
  4687. if not obj_list:
  4688. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4689. else:
  4690. try:
  4691. # first get a bounding box to fit all
  4692. for obj in obj_list:
  4693. xmin, ymin, xmax, ymax = obj.bounds()
  4694. xminlist.append(xmin)
  4695. yminlist.append(ymin)
  4696. xmaxlist.append(xmax)
  4697. ymaxlist.append(ymax)
  4698. # get the minimum x,y and maximum x,y for all objects selected
  4699. xminimal = min(xminlist)
  4700. yminimal = min(yminlist)
  4701. xmaximal = max(xmaxlist)
  4702. ymaximal = max(ymaxlist)
  4703. px = 0.5 * (xminimal + xmaximal)
  4704. py = 0.5 * (yminimal + ymaximal)
  4705. # execute mirroring
  4706. for obj in obj_list:
  4707. obj.mirror('X', [px, py])
  4708. obj.plot()
  4709. self.app_obj.object_changed.emit(obj)
  4710. self.inform.emit('[success] %s' %
  4711. _("Flip on Y axis done."))
  4712. except Exception as e:
  4713. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4714. return
  4715. def on_flipx(self):
  4716. """
  4717. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4718. :return:
  4719. """
  4720. self.defaults.report_usage("on_flipx()")
  4721. obj_list = self.collection.get_selected()
  4722. xminlist = []
  4723. yminlist = []
  4724. xmaxlist = []
  4725. ymaxlist = []
  4726. if not obj_list:
  4727. self.inform.emit('[WARNING_NOTCL] %s' %
  4728. _("No object selected to Flip on X axis."))
  4729. else:
  4730. try:
  4731. # first get a bounding box to fit all
  4732. for obj in obj_list:
  4733. xmin, ymin, xmax, ymax = obj.bounds()
  4734. xminlist.append(xmin)
  4735. yminlist.append(ymin)
  4736. xmaxlist.append(xmax)
  4737. ymaxlist.append(ymax)
  4738. # get the minimum x,y and maximum x,y for all objects selected
  4739. xminimal = min(xminlist)
  4740. yminimal = min(yminlist)
  4741. xmaximal = max(xmaxlist)
  4742. ymaximal = max(ymaxlist)
  4743. px = 0.5 * (xminimal + xmaximal)
  4744. py = 0.5 * (yminimal + ymaximal)
  4745. # execute mirroring
  4746. for obj in obj_list:
  4747. obj.mirror('Y', [px, py])
  4748. obj.plot()
  4749. self.app_obj.object_changed.emit(obj)
  4750. self.inform.emit('[success] %s' %
  4751. _("Flip on X axis done."))
  4752. except Exception as e:
  4753. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4754. return
  4755. def on_rotate(self, silent=False, preset=None):
  4756. """
  4757. Executed when Options -> Rotate Selection menu entry is clicked.
  4758. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4759. :param preset: A value to be used as predefined angle for rotation.
  4760. :return:
  4761. """
  4762. self.defaults.report_usage("on_rotate()")
  4763. obj_list = self.collection.get_selected()
  4764. xminlist = []
  4765. yminlist = []
  4766. xmaxlist = []
  4767. ymaxlist = []
  4768. if not obj_list:
  4769. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4770. else:
  4771. if silent is False:
  4772. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4773. min=-360, max=360, decimals=4,
  4774. init_val=float(self.defaults['tools_transform_rotate']))
  4775. num, ok = rotatebox.get_value()
  4776. else:
  4777. num = preset
  4778. ok = True
  4779. if ok:
  4780. try:
  4781. # first get a bounding box to fit all
  4782. for obj in obj_list:
  4783. xmin, ymin, xmax, ymax = obj.bounds()
  4784. xminlist.append(xmin)
  4785. yminlist.append(ymin)
  4786. xmaxlist.append(xmax)
  4787. ymaxlist.append(ymax)
  4788. # get the minimum x,y and maximum x,y for all objects selected
  4789. xminimal = min(xminlist)
  4790. yminimal = min(yminlist)
  4791. xmaximal = max(xmaxlist)
  4792. ymaximal = max(ymaxlist)
  4793. px = 0.5 * (xminimal + xmaximal)
  4794. py = 0.5 * (yminimal + ymaximal)
  4795. for sel_obj in obj_list:
  4796. sel_obj.rotate(-float(num), point=(px, py))
  4797. sel_obj.plot()
  4798. self.app_obj.object_changed.emit(sel_obj)
  4799. self.inform.emit('[success] %s' % _("Rotation done."))
  4800. except Exception as e:
  4801. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4802. return
  4803. def on_skewx(self):
  4804. """
  4805. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4806. :return:
  4807. """
  4808. self.defaults.report_usage("on_skewx()")
  4809. obj_list = self.collection.get_selected()
  4810. xminlist = []
  4811. yminlist = []
  4812. if not obj_list:
  4813. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4814. else:
  4815. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4816. min=-360, max=360, decimals=4,
  4817. init_val=float(self.defaults['tools_transform_skew_x']))
  4818. num, ok = skewxbox.get_value()
  4819. if ok:
  4820. # first get a bounding box to fit all
  4821. for obj in obj_list:
  4822. xmin, ymin, xmax, ymax = obj.bounds()
  4823. xminlist.append(xmin)
  4824. yminlist.append(ymin)
  4825. # get the minimum x,y and maximum x,y for all objects selected
  4826. xminimal = min(xminlist)
  4827. yminimal = min(yminlist)
  4828. for obj in obj_list:
  4829. obj.skew(num, 0, point=(xminimal, yminimal))
  4830. obj.plot()
  4831. self.app_obj.object_changed.emit(obj)
  4832. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4833. def on_skewy(self):
  4834. """
  4835. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4836. :return:
  4837. """
  4838. self.defaults.report_usage("on_skewy()")
  4839. obj_list = self.collection.get_selected()
  4840. xminlist = []
  4841. yminlist = []
  4842. if not obj_list:
  4843. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4844. else:
  4845. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4846. min=-360, max=360, decimals=4,
  4847. init_val=float(self.defaults['tools_transform_skew_y']))
  4848. num, ok = skewybox.get_value()
  4849. if ok:
  4850. # first get a bounding box to fit all
  4851. for obj in obj_list:
  4852. xmin, ymin, xmax, ymax = obj.bounds()
  4853. xminlist.append(xmin)
  4854. yminlist.append(ymin)
  4855. # get the minimum x,y and maximum x,y for all objects selected
  4856. xminimal = min(xminlist)
  4857. yminimal = min(yminlist)
  4858. for obj in obj_list:
  4859. obj.skew(0, num, point=(xminimal, yminimal))
  4860. obj.plot()
  4861. self.app_obj.object_changed.emit(obj)
  4862. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4863. def on_plots_updated(self):
  4864. """
  4865. Callback used to report when the plots have changed.
  4866. Adjust axes and zooms to fit.
  4867. :return: None
  4868. """
  4869. if self.is_legacy is False:
  4870. self.plotcanvas.update()
  4871. else:
  4872. self.plotcanvas.auto_adjust_axes()
  4873. self.on_zoom_fit()
  4874. self.collection.update_view()
  4875. # self.inform.emit(_("Plots updated ..."))
  4876. def on_toolbar_replot(self):
  4877. """
  4878. Callback for toolbar button. Re-plots all objects.
  4879. :return: None
  4880. """
  4881. self.log.debug("on_toolbar_replot()")
  4882. try:
  4883. obj = self.collection.get_active()
  4884. if obj:
  4885. obj.read_form()
  4886. else:
  4887. self.on_zoom_fit()
  4888. except AttributeError as e:
  4889. log.debug("on_toolbar_replot() -> %s" % str(e))
  4890. pass
  4891. self.plot_all()
  4892. def grid_status(self):
  4893. return True if self.ui.grid_snap_btn.isChecked() else False
  4894. def populate_cmenu_grids(self):
  4895. units = self.defaults['units'].lower()
  4896. # for act in self.ui.cmenu_gridmenu.actions():
  4897. # act.triggered.disconnect()
  4898. self.ui.cmenu_gridmenu.clear()
  4899. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4900. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4901. _("Grid On/Off"))
  4902. grid_toggle.setCheckable(True)
  4903. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4904. self.ui.cmenu_gridmenu.addSeparator()
  4905. for grid in sorted_list:
  4906. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4907. "%s" % str(grid))
  4908. action.triggered.connect(self.set_grid)
  4909. self.ui.cmenu_gridmenu.addSeparator()
  4910. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4911. _("Add"))
  4912. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4913. _("Delete"))
  4914. grid_add.triggered.connect(self.on_grid_add)
  4915. grid_delete.triggered.connect(self.on_grid_delete)
  4916. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4917. def set_grid(self):
  4918. menu_action = self.sender()
  4919. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4920. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4921. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4922. def on_grid_add(self):
  4923. # ## Current application units in lower Case
  4924. units = self.defaults['units'].lower()
  4925. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4926. text=_('Enter a Grid Value:'),
  4927. min=0.0000, max=99.9999, decimals=4)
  4928. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4929. val, ok = grid_add_popup.get_value()
  4930. if ok:
  4931. if float(val) == 0:
  4932. self.inform.emit('[WARNING_NOTCL] %s' %
  4933. _("Please enter a grid value with non-zero value, in Float format."))
  4934. return
  4935. else:
  4936. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4937. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4938. self.inform.emit('[success] %s...' % _("New Grid added"))
  4939. else:
  4940. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4941. else:
  4942. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4943. def on_grid_delete(self):
  4944. # ## Current application units in lower Case
  4945. units = self.defaults['units'].lower()
  4946. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4947. text='Enter a Grid Value:',
  4948. min=0.0000, max=99.9999, decimals=4)
  4949. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4950. val, ok = grid_del_popup.get_value()
  4951. if ok:
  4952. if float(val) == 0:
  4953. self.inform.emit('[WARNING_NOTCL] %s' %
  4954. _("Please enter a grid value with non-zero value, in Float format."))
  4955. return
  4956. else:
  4957. try:
  4958. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4959. except ValueError:
  4960. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4961. return
  4962. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4963. else:
  4964. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4965. def on_shortcut_list(self):
  4966. self.defaults.report_usage("on_shortcut_list()")
  4967. # add the tab if it was closed
  4968. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4969. # delete the absolute and relative position and messages in the infobar
  4970. # self.ui.position_label.setText("")
  4971. # self.ui.rel_position_label.setText("")
  4972. # hide coordinates toolbars in the infobar while in DB
  4973. self.ui.coords_toolbar.hide()
  4974. self.ui.delta_coords_toolbar.hide()
  4975. # Switch plot_area to preferences page
  4976. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4977. # self.ui.show()
  4978. def on_select_tab(self, name):
  4979. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4980. if self.ui.splitter.sizes()[0] == 0:
  4981. self.ui.splitter.setSizes([1, 1])
  4982. else:
  4983. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4984. self.ui.splitter.setSizes([0, 1])
  4985. if name == 'project':
  4986. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4987. elif name == 'selected':
  4988. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4989. elif name == 'tool':
  4990. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4991. def on_copy_name(self):
  4992. self.defaults.report_usage("on_copy_name()")
  4993. obj = self.collection.get_active()
  4994. try:
  4995. name = obj.options["name"]
  4996. except AttributeError:
  4997. log.debug("on_copy_name() --> No object selected to copy it's name")
  4998. self.inform.emit('[WARNING_NOTCL] %s' %
  4999. _(" No object selected to copy it's name"))
  5000. return
  5001. self.clipboard.setText(name)
  5002. self.inform.emit(_("Name copied on clipboard ..."))
  5003. def on_mouse_click_over_plot(self, event):
  5004. """
  5005. Default actions are:
  5006. :param event: Contains information about the event, like which button
  5007. was clicked, the pixel coordinates and the axes coordinates.
  5008. :return: None
  5009. """
  5010. self.pos = []
  5011. if self.is_legacy is False:
  5012. event_pos = event.pos
  5013. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5014. # # Set the mouse button for panning
  5015. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5016. else:
  5017. event_pos = (event.xdata, event.ydata)
  5018. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5019. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5020. # So it can receive key presses
  5021. self.plotcanvas.native.setFocus()
  5022. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5023. if self.grid_status():
  5024. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5025. else:
  5026. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5027. try:
  5028. if event.button == 1:
  5029. # Reset here the relative coordinates so there is a new reference on the click position
  5030. if self.rel_point1 is None:
  5031. self.rel_point1 = self.pos
  5032. else:
  5033. self.rel_point2 = copy(self.rel_point1)
  5034. self.rel_point1 = self.pos
  5035. self.on_mouse_move_over_plot(event, origin_click=True)
  5036. except Exception as e:
  5037. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5038. def on_mouse_double_click_over_plot(self, event):
  5039. if event.button == 1:
  5040. self.doubleclick = True
  5041. def on_mouse_move_over_plot(self, event, origin_click=None):
  5042. """
  5043. Callback for the mouse motion event over the plot.
  5044. :param event: Contains information about the event.
  5045. :param origin_click
  5046. :return: None
  5047. """
  5048. if self.is_legacy is False:
  5049. event_pos = event.pos
  5050. if self.defaults["global_pan_button"] == '2':
  5051. pan_button = 2
  5052. else:
  5053. pan_button = 3
  5054. self.event_is_dragging = event.is_dragging
  5055. else:
  5056. event_pos = (event.xdata, event.ydata)
  5057. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5058. if self.defaults["global_pan_button"] == '2':
  5059. pan_button = 3
  5060. else:
  5061. pan_button = 2
  5062. self.event_is_dragging = self.plotcanvas.is_dragging
  5063. # So it can receive key presses but not when the Tcl Shell is active
  5064. if not self.ui.shell_dock.isVisible():
  5065. if not self.plotcanvas.native.hasFocus():
  5066. self.plotcanvas.native.setFocus()
  5067. self.pos_jump = event_pos
  5068. self.ui.popMenu.mouse_is_panning = False
  5069. if origin_click is None:
  5070. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5071. if event.button == pan_button and self.event_is_dragging == 1:
  5072. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5073. if self.ui.popMenu.popup_active:
  5074. self.ui.popMenu.popup_active = False
  5075. return
  5076. self.ui.popMenu.mouse_is_panning = True
  5077. return
  5078. if self.rel_point1 is not None:
  5079. try: # May fail in case mouse not within axes
  5080. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5081. if pos_canvas[0] is None or pos_canvas[1] is None:
  5082. return
  5083. if self.grid_status():
  5084. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5085. # Update cursor
  5086. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5087. symbol='++', edge_color=self.cursor_color_3D,
  5088. edge_width=self.defaults["global_cursor_width"],
  5089. size=self.defaults["global_cursor_size"])
  5090. else:
  5091. pos = (pos_canvas[0], pos_canvas[1])
  5092. self.dx = pos[0] - float(self.rel_point1[0])
  5093. self.dy = pos[1] - float(self.rel_point1[1])
  5094. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5095. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5096. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5097. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5098. units = self.defaults["units"].lower()
  5099. self.plotcanvas.text_hud.text = \
  5100. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5101. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5102. self.mouse = [pos[0], pos[1]]
  5103. if self.defaults['global_selection_shape'] is False:
  5104. self.selection_type = None
  5105. return
  5106. # if the mouse is moved and the LMB is clicked then the action is a selection
  5107. if self.event_is_dragging == 1 and event.button == 1:
  5108. self.delete_selection_shape()
  5109. if self.dx < 0:
  5110. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5111. face_color=self.defaults['global_alt_sel_fill'])
  5112. self.selection_type = False
  5113. elif self.dx >= 0:
  5114. self.draw_moving_selection_shape(self.pos, pos)
  5115. self.selection_type = True
  5116. else:
  5117. self.selection_type = None
  5118. else:
  5119. self.selection_type = None
  5120. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5121. if self.defaults['global_hover']:
  5122. for obj in self.collection.get_list():
  5123. try:
  5124. # select the object(s) only if it is enabled (plotted)
  5125. if obj.options['plot']:
  5126. if obj not in self.collection.get_selected():
  5127. poly_obj = Polygon(
  5128. [(obj.options['xmin'], obj.options['ymin']),
  5129. (obj.options['xmax'], obj.options['ymin']),
  5130. (obj.options['xmax'], obj.options['ymax']),
  5131. (obj.options['xmin'], obj.options['ymax'])]
  5132. )
  5133. if Point(pos).within(poly_obj):
  5134. if obj.isHovering is False:
  5135. obj.isHovering = True
  5136. obj.notHovering = True
  5137. # create the selection box around the selected object
  5138. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5139. else:
  5140. if obj.notHovering is True:
  5141. obj.notHovering = False
  5142. obj.isHovering = False
  5143. self.delete_hover_shape()
  5144. except Exception:
  5145. # the Exception here will happen if we try to select on screen and we have an
  5146. # newly (and empty) just created Geometry or Excellon object that do not have the
  5147. # xmin, xmax, ymin, ymax options.
  5148. # In this case poly_obj creation (see above) will fail
  5149. pass
  5150. except Exception as e:
  5151. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5152. self.ui.position_label.setText("")
  5153. self.ui.rel_position_label.setText("")
  5154. self.mouse = None
  5155. def on_mouse_click_release_over_plot(self, event):
  5156. """
  5157. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5158. and has been registered in ''self.__init__()''.
  5159. :param event: contains information about the event.
  5160. :return:
  5161. """
  5162. if self.is_legacy is False:
  5163. event_pos = event.pos
  5164. right_button = 2
  5165. else:
  5166. event_pos = (event.xdata, event.ydata)
  5167. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5168. right_button = 3
  5169. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5170. if self.grid_status():
  5171. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5172. else:
  5173. pos = (pos_canvas[0], pos_canvas[1])
  5174. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5175. # canvas menu
  5176. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5177. self.ui.popMenu.mouse_is_panning = False
  5178. self.cursor = QtGui.QCursor()
  5179. self.populate_cmenu_grids()
  5180. self.ui.popMenu.popup(self.cursor.pos())
  5181. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5182. # selection and then select a type of selection ("enclosing" or "touching")
  5183. if event.button == 1: # left click
  5184. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5185. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5186. if modifiers == QtCore.Qt.ShiftModifier:
  5187. # do not auto open the Project Tab
  5188. self.click_noproject = True
  5189. self.clipboard.setText(
  5190. self.defaults["global_point_clipboard_format"] %
  5191. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5192. )
  5193. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5194. return
  5195. if self.doubleclick is True:
  5196. self.doubleclick = False
  5197. if self.collection.get_selected():
  5198. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5199. if self.ui.splitter.sizes()[0] == 0:
  5200. self.ui.splitter.setSizes([1, 1])
  5201. try:
  5202. # delete the selection shape(S) as it may be in the way
  5203. self.delete_selection_shape()
  5204. self.delete_hover_shape()
  5205. except Exception as e:
  5206. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5207. return
  5208. else:
  5209. # WORKAROUND for LEGACY MODE
  5210. if self.is_legacy is True:
  5211. # if there is no move on canvas then we have no dragging selection
  5212. if self.dx == 0 or self.dy == 0:
  5213. self.selection_type = None
  5214. if self.selection_type is not None:
  5215. try:
  5216. self.selection_area_handler(self.pos, pos, self.selection_type)
  5217. self.selection_type = None
  5218. except Exception as e:
  5219. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5220. return
  5221. else:
  5222. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5223. if key_modifier == QtCore.Qt.ShiftModifier:
  5224. mod_key = 'Shift'
  5225. elif key_modifier == QtCore.Qt.ControlModifier:
  5226. mod_key = 'Control'
  5227. else:
  5228. mod_key = None
  5229. try:
  5230. if self.command_active is None:
  5231. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5232. # deselect, and if it's not selected then it will be selected
  5233. # If there is no active command (self.command_active is None) then we check if we clicked
  5234. # on a object by checking the bounding limits against mouse click position
  5235. if mod_key == self.defaults["global_mselect_key"]:
  5236. self.select_objects(key='multisel')
  5237. else:
  5238. # If there is no active command (self.command_active is None) then we check if
  5239. # we clicked on a object by checking the bounding limits against mouse click position
  5240. self.select_objects()
  5241. self.delete_hover_shape()
  5242. except Exception as e:
  5243. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5244. return
  5245. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5246. """
  5247. :param start_pos: mouse position when the selection LMB click was done
  5248. :param end_pos: mouse position when the left mouse button is released
  5249. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5250. :return:
  5251. """
  5252. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5253. # delete previous selection shape
  5254. self.delete_selection_shape()
  5255. # make all objects inactive
  5256. self.collection.set_all_inactive()
  5257. for obj in self.collection.get_list():
  5258. try:
  5259. # select the object(s) only if it is enabled (plotted)
  5260. if obj.options['plot']:
  5261. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5262. (obj.options['xmax'], obj.options['ymin']),
  5263. (obj.options['xmax'], obj.options['ymax']),
  5264. (obj.options['xmin'], obj.options['ymax'])])
  5265. if sel_type is True:
  5266. if poly_obj.within(poly_selection):
  5267. # create the selection box around the selected object
  5268. if self.defaults['global_selection_shape'] is True:
  5269. self.draw_selection_shape(obj)
  5270. self.collection.set_active(obj.options['name'])
  5271. else:
  5272. if poly_selection.intersects(poly_obj):
  5273. # create the selection box around the selected object
  5274. if self.defaults['global_selection_shape'] is True:
  5275. self.draw_selection_shape(obj)
  5276. self.collection.set_active(obj.options['name'])
  5277. obj.selection_shape_drawn = True
  5278. except Exception as e:
  5279. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5280. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5281. # In this case poly_obj creation (see above) will fail
  5282. log.debug("App.selection_area_handler() --> %s" % str(e))
  5283. def select_objects(self, key=None):
  5284. """
  5285. Will select objects clicked on canvas
  5286. :param key: for future use in cumulative selection
  5287. :return:
  5288. """
  5289. # list where we store the overlapped objects under our mouse left click position
  5290. if key is None:
  5291. self.objects_under_the_click_list = []
  5292. # Populate the list with the overlapped objects on the click position
  5293. curr_x, curr_y = self.pos
  5294. for obj in self.all_objects_list:
  5295. # ScriptObject and DocumentObject objects can't be selected
  5296. if obj.kind == 'script' or obj.kind == 'document':
  5297. continue
  5298. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5299. continue
  5300. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5301. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5302. if obj.options['name'] not in self.objects_under_the_click_list:
  5303. if obj.options['plot']:
  5304. # add objects to the objects_under_the_click list only if the object is plotted
  5305. # (active and not disabled)
  5306. self.objects_under_the_click_list.append(obj.options['name'])
  5307. try:
  5308. if self.objects_under_the_click_list:
  5309. curr_sel_obj = self.collection.get_active()
  5310. # case when there is only an object under the click and we toggle it
  5311. if len(self.objects_under_the_click_list) == 1:
  5312. if curr_sel_obj is None:
  5313. self.collection.set_active(self.objects_under_the_click_list[0])
  5314. curr_sel_obj = self.collection.get_active()
  5315. # create the selection box around the selected object
  5316. if self.defaults['global_selection_shape'] is True:
  5317. self.draw_selection_shape(curr_sel_obj)
  5318. curr_sel_obj.selection_shape_drawn = True
  5319. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5320. self.collection.on_objects_selection(False)
  5321. self.delete_selection_shape()
  5322. curr_sel_obj.selection_shape_drawn = False
  5323. self.collection.set_active(self.objects_under_the_click_list[0])
  5324. curr_sel_obj = self.collection.get_active()
  5325. # create the selection box around the selected object
  5326. if self.defaults['global_selection_shape'] is True:
  5327. self.draw_selection_shape(curr_sel_obj)
  5328. curr_sel_obj.selection_shape_drawn = True
  5329. self.selected_message(curr_sel_obj=curr_sel_obj)
  5330. elif curr_sel_obj.selection_shape_drawn is False:
  5331. if self.defaults['global_selection_shape'] is True:
  5332. self.draw_selection_shape(curr_sel_obj)
  5333. curr_sel_obj.selection_shape_drawn = True
  5334. else:
  5335. self.collection.on_objects_selection(False)
  5336. self.delete_selection_shape()
  5337. if self.call_source != 'app':
  5338. self.call_source = 'app'
  5339. self.selected_message(curr_sel_obj=curr_sel_obj)
  5340. else:
  5341. # If there is no selected object
  5342. # make active the first element of the overlapped objects list
  5343. if self.collection.get_active() is None:
  5344. self.collection.set_active(self.objects_under_the_click_list[0])
  5345. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5346. name_sel_obj = self.collection.get_active().options['name']
  5347. # In case that there is a selected object but it is not in the overlapped object list
  5348. # make that object inactive and activate the first element in the overlapped object list
  5349. if name_sel_obj not in self.objects_under_the_click_list:
  5350. self.collection.set_inactive(name_sel_obj)
  5351. name_sel_obj = self.objects_under_the_click_list[0]
  5352. self.collection.set_active(name_sel_obj)
  5353. else:
  5354. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5355. self.collection.set_all_inactive()
  5356. self.collection.set_active(
  5357. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5358. curr_sel_obj = self.collection.get_active()
  5359. # delete the possible selection box around a possible selected object
  5360. self.delete_selection_shape()
  5361. curr_sel_obj.selection_shape_drawn = False
  5362. # create the selection box around the selected object
  5363. if self.defaults['global_selection_shape'] is True:
  5364. self.draw_selection_shape(curr_sel_obj)
  5365. curr_sel_obj.selection_shape_drawn = True
  5366. self.selected_message(curr_sel_obj=curr_sel_obj)
  5367. else:
  5368. # deselect everything
  5369. self.collection.on_objects_selection(False)
  5370. # delete the possible selection box around a possible selected object
  5371. self.delete_selection_shape()
  5372. for o in self.collection.get_list():
  5373. o.selection_shape_drawn = False
  5374. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5375. # only when working on App
  5376. if self.call_source == 'app':
  5377. if self.click_noproject is False:
  5378. # if the Tool Tab is in focus don't change focus to Project Tab
  5379. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5380. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5381. else:
  5382. # restore auto open the Project Tab
  5383. self.click_noproject = False
  5384. # delete any text in the status bar, implicitly the last object name that was selected
  5385. # self.inform.emit("")
  5386. else:
  5387. self.call_source = 'app'
  5388. except Exception as e:
  5389. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5390. def selected_message(self, curr_sel_obj):
  5391. if curr_sel_obj:
  5392. if curr_sel_obj.kind == 'gerber':
  5393. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5394. color='green',
  5395. name=str(curr_sel_obj.options['name']),
  5396. tx=_("selected"))
  5397. )
  5398. elif curr_sel_obj.kind == 'excellon':
  5399. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5400. color='brown',
  5401. name=str(curr_sel_obj.options['name']),
  5402. tx=_("selected"))
  5403. )
  5404. elif curr_sel_obj.kind == 'cncjob':
  5405. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5406. color='blue',
  5407. name=str(curr_sel_obj.options['name']),
  5408. tx=_("selected"))
  5409. )
  5410. elif curr_sel_obj.kind == 'geometry':
  5411. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5412. color='red',
  5413. name=str(curr_sel_obj.options['name']),
  5414. tx=_("selected"))
  5415. )
  5416. def delete_hover_shape(self):
  5417. self.hover_shapes.clear()
  5418. self.hover_shapes.redraw()
  5419. def draw_hover_shape(self, sel_obj, color=None):
  5420. """
  5421. :param sel_obj: The object for which the hover shape must be drawn
  5422. :param color: The color of the hover shape
  5423. :return: None
  5424. """
  5425. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5426. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5427. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5428. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5429. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5430. if self.defaults['units'].upper() == 'MM':
  5431. hover_rect = hover_rect.buffer(-0.1)
  5432. hover_rect = hover_rect.buffer(0.2)
  5433. else:
  5434. hover_rect = hover_rect.buffer(-0.00393)
  5435. hover_rect = hover_rect.buffer(0.00787)
  5436. # if color:
  5437. # face = Color(color)
  5438. # face.alpha = 0.2
  5439. # outline = Color(color, alpha=0.8)
  5440. # else:
  5441. # face = Color(self.defaults['global_sel_fill'])
  5442. # face.alpha = 0.2
  5443. # outline = self.defaults['global_sel_line']
  5444. if color:
  5445. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5446. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5447. else:
  5448. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5449. outline = self.defaults['global_sel_line']
  5450. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5451. if self.is_legacy is True:
  5452. self.hover_shapes.redraw()
  5453. def delete_selection_shape(self):
  5454. self.move_tool.sel_shapes.clear()
  5455. self.move_tool.sel_shapes.redraw()
  5456. def draw_selection_shape(self, sel_obj, color=None):
  5457. """
  5458. Will draw a selection shape around the selected object.
  5459. :param sel_obj: The object for which the selection shape must be drawn
  5460. :param color: The color for the selection shape.
  5461. :return: None
  5462. """
  5463. if sel_obj is None:
  5464. return
  5465. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5466. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5467. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5468. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5469. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5470. if self.defaults['units'].upper() == 'MM':
  5471. sel_rect = sel_rect.buffer(-0.1)
  5472. sel_rect = sel_rect.buffer(0.2)
  5473. else:
  5474. sel_rect = sel_rect.buffer(-0.00393)
  5475. sel_rect = sel_rect.buffer(0.00787)
  5476. if color:
  5477. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5478. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5479. else:
  5480. if self.is_legacy is False:
  5481. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5482. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5483. else:
  5484. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5485. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5486. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5487. color=outline,
  5488. face_color=face,
  5489. update=True,
  5490. layer=0,
  5491. tolerance=None))
  5492. if self.is_legacy is True:
  5493. self.move_tool.sel_shapes.redraw()
  5494. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5495. """
  5496. Will draw a selection shape when dragging mouse on canvas.
  5497. :param old_coords: Old coordinates
  5498. :param coords: New coordinates
  5499. :param kwargs: Keyword arguments
  5500. :return:
  5501. """
  5502. if 'color' in kwargs:
  5503. color = kwargs['color']
  5504. else:
  5505. color = self.defaults['global_sel_line']
  5506. if 'face_color' in kwargs:
  5507. face_color = kwargs['face_color']
  5508. else:
  5509. face_color = self.defaults['global_sel_fill']
  5510. if 'face_alpha' in kwargs:
  5511. face_alpha = kwargs['face_alpha']
  5512. else:
  5513. face_alpha = 0.3
  5514. x0, y0 = old_coords
  5515. x1, y1 = coords
  5516. pt1 = (x0, y0)
  5517. pt2 = (x1, y0)
  5518. pt3 = (x1, y1)
  5519. pt4 = (x0, y1)
  5520. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5521. # color_t = Color(face_color)
  5522. # color_t.alpha = face_alpha
  5523. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5524. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5525. layer=0, tolerance=None)
  5526. if self.is_legacy is True:
  5527. self.move_tool.sel_shapes.redraw()
  5528. def on_file_new_click(self):
  5529. """
  5530. Callback for menu item File -> New.
  5531. Executed on clicking the Menu -> File -> New Project
  5532. :return:
  5533. """
  5534. if self.collection.get_list() and self.should_we_save:
  5535. msgbox = QtWidgets.QMessageBox()
  5536. # msgbox.setText("<B>Save changes ...</B>")
  5537. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5538. "Creating a New project will delete them.\n"
  5539. "Do you want to Save the project?"))
  5540. msgbox.setWindowTitle(_("Save changes"))
  5541. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5542. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5543. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5544. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5545. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5546. msgbox.setDefaultButton(bt_yes)
  5547. msgbox.exec_()
  5548. response = msgbox.clickedButton()
  5549. if response == bt_yes:
  5550. self.on_file_saveprojectas()
  5551. elif response == bt_cancel:
  5552. return
  5553. elif response == bt_no:
  5554. self.on_file_new()
  5555. else:
  5556. self.on_file_new()
  5557. self.inform.emit('[success] %s...' % _("New Project created"))
  5558. def on_file_new(self, cli=None):
  5559. """
  5560. Returns the application to its startup state. This method is thread-safe.
  5561. :param cli: Boolean. If True this method was run from command line
  5562. :return: None
  5563. """
  5564. self.defaults.report_usage("on_file_new")
  5565. # Remove everything from memory
  5566. App.log.debug("on_file_new()")
  5567. # close any editor that might be open
  5568. if self.call_source != 'app':
  5569. self.editor2object(cleanup=True)
  5570. # ## EDITOR section
  5571. self.geo_editor = AppGeoEditor(self)
  5572. self.exc_editor = AppExcEditor(self)
  5573. self.grb_editor = AppGerberEditor(self)
  5574. # Clear pool
  5575. self.clear_pool()
  5576. for obj in self.collection.get_list():
  5577. # delete shapes left drawn from mark shape_collections, if any
  5578. if isinstance(obj, GerberObject):
  5579. try:
  5580. obj.mark_shapes_storage.clear()
  5581. obj.mark_shapes.clear(update=True)
  5582. obj.mark_shapes.enabled = False
  5583. except AttributeError:
  5584. pass
  5585. # also delete annotation shapes, if any
  5586. elif isinstance(obj, CNCJobObject):
  5587. try:
  5588. obj.text_col.enabled = False
  5589. del obj.text_col
  5590. obj.annotation.clear(update=True)
  5591. del obj.annotation
  5592. except AttributeError:
  5593. pass
  5594. # delete the exclusion areas
  5595. self.exc_areas.clear_shapes()
  5596. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5597. self.shell.init_tcl()
  5598. # delete any selection shape on canvas
  5599. self.delete_selection_shape()
  5600. # delete all FlatCAM objects
  5601. self.collection.delete_all()
  5602. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5603. self.setup_component_editor()
  5604. # Clear project filename
  5605. self.project_filename = None
  5606. # Load the application defaults
  5607. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5608. # Re-fresh project options
  5609. self.on_options_app2project()
  5610. # Init FlatCAMTools
  5611. self.init_tools()
  5612. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5613. if cli is None:
  5614. # we need to go in reverse because once we remove a tab then the index changes
  5615. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5616. # and so on. Therefore the deletion should be done in reverse
  5617. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5618. for index in range(wdg_count, -1, -1):
  5619. try:
  5620. self.ui.plot_tab_area.closeTab(index)
  5621. except Exception as e:
  5622. log.debug("App.on_file_new() --> %s" % str(e))
  5623. # # And then add again the Plot Area
  5624. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5625. self.ui.plot_tab_area.protectTab(0)
  5626. # take the focus of the Notebook on Project Tab.
  5627. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5628. self.set_ui_title(name=_("New Project - Not saved"))
  5629. def obj_properties(self):
  5630. """
  5631. Will launch the object Properties Tool
  5632. :return:
  5633. """
  5634. self.defaults.report_usage("obj_properties()")
  5635. self.properties_tool.run(toggle=False)
  5636. def on_project_context_save(self):
  5637. """
  5638. Wrapper, will save the object function of it's type
  5639. :return:
  5640. """
  5641. sel_objects = self.collection.get_selected()
  5642. len_objects = len(sel_objects)
  5643. cnt = 0
  5644. if len_objects > 1:
  5645. for o in sel_objects:
  5646. if o.kind == 'cncjob':
  5647. cnt += 1
  5648. if len_objects == cnt:
  5649. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5650. _filter_ = self.defaults['cncjob_save_filters'] + \
  5651. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5652. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5653. try:
  5654. filename, _f = FCFileSaveDialog.get_saved_filename(
  5655. caption=_("Export Code ..."),
  5656. directory=dir_file_to_save,
  5657. ext_filter=_filter_
  5658. )
  5659. except TypeError:
  5660. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5661. ext_filter=_filter_)
  5662. filename = filename.rpartition('/')[0]
  5663. for ob in sel_objects:
  5664. ob.read_form()
  5665. fname = '%s/%s' % (filename, ob.options['name'])
  5666. ob.export_gcode_handler(fname, is_gcode=True)
  5667. return
  5668. obj = self.collection.get_active()
  5669. if type(obj) == GeometryObject:
  5670. self.on_file_exportdxf()
  5671. elif type(obj) == ExcellonObject:
  5672. self.on_file_saveexcellon()
  5673. elif type(obj) == CNCJobObject:
  5674. obj.on_exportgcode_button_click()
  5675. elif type(obj) == GerberObject:
  5676. self.on_file_savegerber()
  5677. elif type(obj) == ScriptObject:
  5678. self.on_file_savescript()
  5679. elif type(obj) == DocumentObject:
  5680. self.on_file_savedocument()
  5681. def obj_move(self):
  5682. """
  5683. Callback for the Move menu entry in various Context Menu's.
  5684. :return:
  5685. """
  5686. self.defaults.report_usage("obj_move()")
  5687. self.move_tool.run(toggle=False)
  5688. def on_fileopengerber(self, signal, name=None):
  5689. """
  5690. File menu callback for opening a Gerber.
  5691. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5692. :param name:
  5693. :return: None
  5694. """
  5695. self.defaults.report_usage("on_fileopengerber")
  5696. App.log.debug("on_fileopengerber()")
  5697. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5698. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5699. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5700. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5701. "*.outline);;" \
  5702. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5703. "*.mil);;" \
  5704. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5705. "Allegro Files (*.art);;" \
  5706. "Mentor Files (*.pho *.gdo);;" \
  5707. "All Files (*.*)"
  5708. if name is None:
  5709. try:
  5710. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5711. directory=self.get_last_folder(),
  5712. filter=_filter_,
  5713. initialFilter=self.last_op_gerber_filter)
  5714. except TypeError:
  5715. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5716. filenames = [str(filename) for filename in filenames]
  5717. self.last_op_gerber_filter = _f
  5718. else:
  5719. filenames = [name]
  5720. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5721. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5722. _("Opening Gerber file.")),
  5723. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5724. color=QtGui.QColor("gray"))
  5725. if len(filenames) == 0:
  5726. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5727. else:
  5728. for filename in filenames:
  5729. if filename != '':
  5730. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5731. def on_fileopenexcellon(self, signal, name=None):
  5732. """
  5733. File menu callback for opening an Excellon file.
  5734. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5735. :param name:
  5736. :return: None
  5737. """
  5738. self.defaults.report_usage("on_fileopenexcellon")
  5739. App.log.debug("on_fileopenexcellon()")
  5740. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5741. "All Files (*.*)"
  5742. if name is None:
  5743. try:
  5744. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5745. directory=self.get_last_folder(),
  5746. filter=_filter_,
  5747. initialFilter=self.last_op_excellon_filter)
  5748. except TypeError:
  5749. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5750. filenames = [str(filename) for filename in filenames]
  5751. self.last_op_excellon_filter = _f
  5752. else:
  5753. filenames = [str(name)]
  5754. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5755. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5756. _("Opening Excellon file.")),
  5757. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5758. color=QtGui.QColor("gray"))
  5759. if len(filenames) == 0:
  5760. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5761. else:
  5762. for filename in filenames:
  5763. if filename != '':
  5764. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5765. def on_fileopengcode(self, signal, name=None):
  5766. """
  5767. File menu call back for opening gcode.
  5768. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5769. :param name:
  5770. :return:
  5771. """
  5772. self.defaults.report_usage("on_fileopengcode")
  5773. App.log.debug("on_fileopengcode()")
  5774. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5775. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5776. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5777. "All Files (*.*)"
  5778. if name is None:
  5779. try:
  5780. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5781. directory=self.get_last_folder(),
  5782. filter=_filter_,
  5783. initialFilter=self.last_op_gcode_filter)
  5784. except TypeError:
  5785. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5786. filenames = [str(filename) for filename in filenames]
  5787. self.last_op_gcode_filter = _f
  5788. else:
  5789. filenames = [name]
  5790. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5791. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5792. _("Opening G-Code file.")),
  5793. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5794. color=QtGui.QColor("gray"))
  5795. if len(filenames) == 0:
  5796. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5797. else:
  5798. for filename in filenames:
  5799. if filename != '':
  5800. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5801. def on_file_openproject(self, signal):
  5802. """
  5803. File menu callback for opening a project.
  5804. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5805. :return: None
  5806. """
  5807. self.defaults.report_usage("on_file_openproject")
  5808. App.log.debug("on_file_openproject()")
  5809. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5810. try:
  5811. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5812. directory=self.get_last_folder(), filter=_filter_)
  5813. except TypeError:
  5814. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5815. # The Qt methods above will return a QString which can cause problems later.
  5816. # So far json.dump() will fail to serialize it.
  5817. # TODO: Improve the serialization methods and remove this fix.
  5818. filename = str(filename)
  5819. if filename == "":
  5820. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5821. else:
  5822. # self.worker_task.emit({'fcn': self.open_project,
  5823. # 'params': [filename]})
  5824. # The above was failing because open_project() is not
  5825. # thread safe. The new_project()
  5826. self.open_project(filename)
  5827. def on_fileopenhpgl2(self, signal, name=None):
  5828. """
  5829. File menu callback for opening a HPGL2.
  5830. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5831. :param name:
  5832. :return: None
  5833. """
  5834. self.defaults.report_usage("on_fileopenhpgl2")
  5835. App.log.debug("on_fileopenhpgl2()")
  5836. _filter_ = "HPGL2 Files (*.plt);;" \
  5837. "All Files (*.*)"
  5838. if name is None:
  5839. try:
  5840. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5841. directory=self.get_last_folder(),
  5842. filter=_filter_)
  5843. except TypeError:
  5844. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5845. filenames = [str(filename) for filename in filenames]
  5846. else:
  5847. filenames = [name]
  5848. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5849. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5850. _("Opening HPGL2 file.")),
  5851. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5852. color=QtGui.QColor("gray"))
  5853. if len(filenames) == 0:
  5854. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5855. else:
  5856. for filename in filenames:
  5857. if filename != '':
  5858. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5859. def on_file_openconfig(self, signal):
  5860. """
  5861. File menu callback for opening a config file.
  5862. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5863. :return: None
  5864. """
  5865. self.defaults.report_usage("on_file_openconfig")
  5866. App.log.debug("on_file_openconfig()")
  5867. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5868. try:
  5869. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5870. directory=self.data_path, filter=_filter_)
  5871. except TypeError:
  5872. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5873. filter=_filter_)
  5874. if filename == "":
  5875. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5876. else:
  5877. self.open_config_file(filename)
  5878. def on_file_exportsvg(self):
  5879. """
  5880. Callback for menu item File->Export SVG.
  5881. :return: None
  5882. """
  5883. self.defaults.report_usage("on_file_exportsvg")
  5884. App.log.debug("on_file_exportsvg()")
  5885. obj = self.collection.get_active()
  5886. if obj is None:
  5887. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5888. msg = _("Please Select a Geometry object to export")
  5889. msgbox = QtWidgets.QMessageBox()
  5890. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5891. msgbox.setInformativeText(msg)
  5892. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5893. msgbox.setDefaultButton(bt_ok)
  5894. msgbox.exec_()
  5895. return
  5896. # Check for more compatible types and add as required
  5897. if (not isinstance(obj, GeometryObject)
  5898. and not isinstance(obj, GerberObject)
  5899. and not isinstance(obj, CNCJobObject)
  5900. and not isinstance(obj, ExcellonObject)):
  5901. msg = '[ERROR_NOTCL] %s' % \
  5902. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5903. msgbox = QtWidgets.QMessageBox()
  5904. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5905. msgbox.setInformativeText(msg)
  5906. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5907. msgbox.setDefaultButton(bt_ok)
  5908. msgbox.exec_()
  5909. return
  5910. name = obj.options["name"]
  5911. _filter = "SVG File (*.svg);;All Files (*.*)"
  5912. try:
  5913. filename, _f = FCFileSaveDialog.get_saved_filename(
  5914. caption=_("Export SVG"),
  5915. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5916. ext_filter=_filter)
  5917. except TypeError:
  5918. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5919. filename = str(filename)
  5920. if filename == "":
  5921. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5922. return
  5923. else:
  5924. self.export_svg(name, filename)
  5925. if self.defaults["global_open_style"] is False:
  5926. self.file_opened.emit("SVG", filename)
  5927. self.file_saved.emit("SVG", filename)
  5928. def on_file_exportpng(self):
  5929. self.defaults.report_usage("on_file_exportpng")
  5930. App.log.debug("on_file_exportpng()")
  5931. self.date = str(datetime.today()).rpartition('.')[0]
  5932. self.date = ''.join(c for c in self.date if c not in ':-')
  5933. self.date = self.date.replace(' ', '_')
  5934. data = None
  5935. if self.is_legacy is False:
  5936. image = _screenshot(alpha=False)
  5937. data = np.asarray(image)
  5938. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5939. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5940. return
  5941. filter_ = "PNG File (*.png);;All Files (*.*)"
  5942. try:
  5943. filename, _f = FCFileSaveDialog.get_saved_filename(
  5944. caption=_("Export PNG Image"),
  5945. directory=self.get_last_save_folder() + '/png_' + self.date,
  5946. ext_filter=filter_)
  5947. except TypeError:
  5948. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5949. filename = str(filename)
  5950. if filename == "":
  5951. self.inform.emit(_("Cancelled."))
  5952. return
  5953. else:
  5954. if self.is_legacy is False:
  5955. write_png(filename, data)
  5956. else:
  5957. self.plotcanvas.figure.savefig(filename)
  5958. if self.defaults["global_open_style"] is False:
  5959. self.file_opened.emit("png", filename)
  5960. self.file_saved.emit("png", filename)
  5961. def on_file_savegerber(self):
  5962. """
  5963. Callback for menu item in Project context menu.
  5964. :return: None
  5965. """
  5966. self.defaults.report_usage("on_file_savegerber")
  5967. App.log.debug("on_file_savegerber()")
  5968. obj = self.collection.get_active()
  5969. if obj is None:
  5970. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5971. return
  5972. # Check for more compatible types and add as required
  5973. if not isinstance(obj, GerberObject):
  5974. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5975. return
  5976. name = self.collection.get_active().options["name"]
  5977. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5978. try:
  5979. filename, _f = FCFileSaveDialog.get_saved_filename(
  5980. caption="Save Gerber source file",
  5981. directory=self.get_last_save_folder() + '/' + name,
  5982. ext_filter=_filter)
  5983. except TypeError:
  5984. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5985. filename = str(filename)
  5986. if filename == "":
  5987. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5988. return
  5989. else:
  5990. self.save_source_file(name, filename)
  5991. if self.defaults["global_open_style"] is False:
  5992. self.file_opened.emit("Gerber", filename)
  5993. self.file_saved.emit("Gerber", filename)
  5994. def on_file_savescript(self):
  5995. """
  5996. Callback for menu item in Project context menu.
  5997. :return: None
  5998. """
  5999. self.defaults.report_usage("on_file_savescript")
  6000. App.log.debug("on_file_savescript()")
  6001. obj = self.collection.get_active()
  6002. if obj is None:
  6003. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6004. return
  6005. # Check for more compatible types and add as required
  6006. if not isinstance(obj, ScriptObject):
  6007. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6008. return
  6009. name = self.collection.get_active().options["name"]
  6010. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6011. try:
  6012. filename, _f = FCFileSaveDialog.get_saved_filename(
  6013. caption="Save Script source file",
  6014. directory=self.get_last_save_folder() + '/' + name,
  6015. ext_filter=_filter)
  6016. except TypeError:
  6017. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  6018. filename = str(filename)
  6019. if filename == "":
  6020. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6021. return
  6022. else:
  6023. self.save_source_file(name, filename)
  6024. if self.defaults["global_open_style"] is False:
  6025. self.file_opened.emit("Script", filename)
  6026. self.file_saved.emit("Script", filename)
  6027. def on_file_savedocument(self):
  6028. """
  6029. Callback for menu item in Project context menu.
  6030. :return: None
  6031. """
  6032. self.defaults.report_usage("on_file_savedocument")
  6033. App.log.debug("on_file_savedocument()")
  6034. obj = self.collection.get_active()
  6035. if obj is None:
  6036. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6037. return
  6038. # Check for more compatible types and add as required
  6039. if not isinstance(obj, ScriptObject):
  6040. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6041. return
  6042. name = self.collection.get_active().options["name"]
  6043. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6044. try:
  6045. filename, _f = FCFileSaveDialog.get_saved_filename(
  6046. caption="Save Document source file",
  6047. directory=self.get_last_save_folder() + '/' + name,
  6048. ext_filter=_filter)
  6049. except TypeError:
  6050. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  6051. ext_filter=_filter)
  6052. filename = str(filename)
  6053. if filename == "":
  6054. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6055. return
  6056. else:
  6057. self.save_source_file(name, filename)
  6058. if self.defaults["global_open_style"] is False:
  6059. self.file_opened.emit("Document", filename)
  6060. self.file_saved.emit("Document", filename)
  6061. def on_file_saveexcellon(self):
  6062. """
  6063. Callback for menu item in project context menu.
  6064. :return: None
  6065. """
  6066. self.defaults.report_usage("on_file_saveexcellon")
  6067. App.log.debug("on_file_saveexcellon()")
  6068. obj = self.collection.get_active()
  6069. if obj is None:
  6070. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6071. return
  6072. # Check for more compatible types and add as required
  6073. if not isinstance(obj, ExcellonObject):
  6074. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6075. return
  6076. name = self.collection.get_active().options["name"]
  6077. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6078. try:
  6079. filename, _f = FCFileSaveDialog.get_saved_filename(
  6080. caption=_("Save Excellon source file"),
  6081. directory=self.get_last_save_folder() + '/' + name,
  6082. ext_filter=_filter)
  6083. except TypeError:
  6084. filename, _f = FCFileSaveDialog.get_saved_filename(
  6085. caption=_("Save Excellon source file"), ext_filter=_filter)
  6086. filename = str(filename)
  6087. if filename == "":
  6088. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6089. return
  6090. else:
  6091. self.save_source_file(name, filename)
  6092. if self.defaults["global_open_style"] is False:
  6093. self.file_opened.emit("Excellon", filename)
  6094. self.file_saved.emit("Excellon", filename)
  6095. def on_file_exportexcellon(self):
  6096. """
  6097. Callback for menu item File->Export->Excellon.
  6098. :return: None
  6099. """
  6100. self.defaults.report_usage("on_file_exportexcellon")
  6101. App.log.debug("on_file_exportexcellon()")
  6102. obj = self.collection.get_active()
  6103. if obj is None:
  6104. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6105. return
  6106. # Check for more compatible types and add as required
  6107. if not isinstance(obj, ExcellonObject):
  6108. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6109. return
  6110. name = self.collection.get_active().options["name"]
  6111. _filter = self.defaults["excellon_save_filters"]
  6112. try:
  6113. filename, _f = FCFileSaveDialog.get_saved_filename(
  6114. caption=_("Export Excellon"),
  6115. directory=self.get_last_save_folder() + '/' + name,
  6116. ext_filter=_filter)
  6117. except TypeError:
  6118. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  6119. filename = str(filename)
  6120. if filename == "":
  6121. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6122. return
  6123. else:
  6124. used_extension = filename.rpartition('.')[2]
  6125. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6126. self.export_excellon(name, filename)
  6127. if self.defaults["global_open_style"] is False:
  6128. self.file_opened.emit("Excellon", filename)
  6129. self.file_saved.emit("Excellon", filename)
  6130. def on_file_exportgerber(self):
  6131. """
  6132. Callback for menu item File->Export->Gerber.
  6133. :return: None
  6134. """
  6135. self.defaults.report_usage("on_file_exportgerber")
  6136. App.log.debug("on_file_exportgerber()")
  6137. obj = self.collection.get_active()
  6138. if obj is None:
  6139. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6140. return
  6141. # Check for more compatible types and add as required
  6142. if not isinstance(obj, GerberObject):
  6143. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6144. return
  6145. name = self.collection.get_active().options["name"]
  6146. _filter_ = self.defaults['gerber_save_filters']
  6147. try:
  6148. filename, _f = FCFileSaveDialog.get_saved_filename(
  6149. caption=_("Export Gerber"),
  6150. directory=self.get_last_save_folder() + '/' + name,
  6151. ext_filter=_filter_)
  6152. except TypeError:
  6153. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6154. filename = str(filename)
  6155. if filename == "":
  6156. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6157. return
  6158. else:
  6159. used_extension = filename.rpartition('.')[2]
  6160. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6161. self.export_gerber(name, filename)
  6162. if self.defaults["global_open_style"] is False:
  6163. self.file_opened.emit("Gerber", filename)
  6164. self.file_saved.emit("Gerber", filename)
  6165. def on_file_exportdxf(self):
  6166. """
  6167. Callback for menu item File->Export DXF.
  6168. :return: None
  6169. """
  6170. self.defaults.report_usage("on_file_exportdxf")
  6171. App.log.debug("on_file_exportdxf()")
  6172. obj = self.collection.get_active()
  6173. if obj is None:
  6174. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6175. msg = _("Please Select a Geometry object to export")
  6176. msgbox = QtWidgets.QMessageBox()
  6177. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6178. msgbox.setInformativeText(msg)
  6179. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6180. msgbox.setDefaultButton(bt_ok)
  6181. msgbox.exec_()
  6182. return
  6183. # Check for more compatible types and add as required
  6184. if not isinstance(obj, GeometryObject):
  6185. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6186. msgbox = QtWidgets.QMessageBox()
  6187. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6188. msgbox.setInformativeText(msg)
  6189. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6190. msgbox.setDefaultButton(bt_ok)
  6191. msgbox.exec_()
  6192. return
  6193. name = self.collection.get_active().options["name"]
  6194. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6195. try:
  6196. filename, _f = FCFileSaveDialog.get_saved_filename(
  6197. caption=_("Export DXF"),
  6198. directory=self.get_last_save_folder() + '/' + name,
  6199. ext_filter=_filter_)
  6200. except TypeError:
  6201. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6202. filename = str(filename)
  6203. if filename == "":
  6204. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6205. return
  6206. else:
  6207. self.export_dxf(name, filename)
  6208. if self.defaults["global_open_style"] is False:
  6209. self.file_opened.emit("DXF", filename)
  6210. self.file_saved.emit("DXF", filename)
  6211. def on_file_importsvg(self, type_of_obj):
  6212. """
  6213. Callback for menu item File->Import SVG.
  6214. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6215. :type type_of_obj: str
  6216. :return: None
  6217. """
  6218. self.defaults.report_usage("on_file_importsvg")
  6219. App.log.debug("on_file_importsvg()")
  6220. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6221. try:
  6222. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6223. directory=self.get_last_folder(), filter=_filter_)
  6224. except TypeError:
  6225. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6226. filter=_filter_)
  6227. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6228. type_of_obj = "geometry"
  6229. filenames = [str(filename) for filename in filenames]
  6230. if len(filenames) == 0:
  6231. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6232. else:
  6233. for filename in filenames:
  6234. if filename != '':
  6235. self.worker_task.emit({'fcn': self.import_svg,
  6236. 'params': [filename, type_of_obj]})
  6237. def on_file_importdxf(self, type_of_obj):
  6238. """
  6239. Callback for menu item File->Import DXF.
  6240. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6241. :type type_of_obj: str
  6242. :return: None
  6243. """
  6244. self.defaults.report_usage("on_file_importdxf")
  6245. App.log.debug("on_file_importdxf()")
  6246. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6247. try:
  6248. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6249. directory=self.get_last_folder(),
  6250. filter=_filter_)
  6251. except TypeError:
  6252. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6253. filter=_filter_)
  6254. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6255. type_of_obj = "geometry"
  6256. filenames = [str(filename) for filename in filenames]
  6257. if len(filenames) == 0:
  6258. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6259. else:
  6260. for filename in filenames:
  6261. if filename != '':
  6262. self.worker_task.emit({'fcn': self.import_dxf,
  6263. 'params': [filename, type_of_obj]})
  6264. # ###############################################################################################################
  6265. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6266. # ###############################################################################################################
  6267. def init_code_editor(self, name):
  6268. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6269. # add the tab if it was closed
  6270. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6271. self.text_editor_tab.setObjectName('text_editor_tab')
  6272. # delete the absolute and relative position and messages in the infobar
  6273. # self.ui.position_label.setText("")
  6274. # self.ui.rel_position_label.setText("")
  6275. # hide coordinates toolbars in the infobar while in DB
  6276. self.ui.coords_toolbar.hide()
  6277. self.ui.delta_coords_toolbar.hide()
  6278. # first clear previous text in text editor (if any)
  6279. self.text_editor_tab.code_editor.clear()
  6280. self.text_editor_tab.code_editor.setReadOnly(False)
  6281. self.toggle_codeeditor = True
  6282. self.text_editor_tab.code_editor.completer_enable = False
  6283. self.text_editor_tab.buttonRun.hide()
  6284. # make sure to keep a reference to the code editor
  6285. self.reference_code_editor = self.text_editor_tab.code_editor
  6286. # Switch plot_area to CNCJob tab
  6287. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6288. def on_view_source(self):
  6289. """
  6290. Called when the user wants to see the source file of the selected object
  6291. :return:
  6292. """
  6293. try:
  6294. obj = self.collection.get_active()
  6295. except Exception as e:
  6296. log.debug("App.on_view_source() --> %s" % str(e))
  6297. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6298. return 'fail'
  6299. if obj is None:
  6300. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6301. return 'fail'
  6302. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6303. self.proc_container.view.set_busy(_("Loading..."))
  6304. flt = "All Files (*.*)"
  6305. if obj.kind == 'gerber':
  6306. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6307. elif obj.kind == 'excellon':
  6308. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6309. elif obj.kind == 'cncjob':
  6310. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6311. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6312. # add the tab if it was closed
  6313. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6314. self.source_editor_tab.setObjectName('source_editor_tab')
  6315. # delete the absolute and relative position and messages in the infobar
  6316. # self.ui.position_label.setText("")
  6317. # self.ui.rel_position_label.setText("")
  6318. # hide coordinates toolbars in the infobar while in DB
  6319. self.ui.coords_toolbar.hide()
  6320. self.ui.delta_coords_toolbar.hide()
  6321. # first clear previous text in text editor (if any)
  6322. self.source_editor_tab.code_editor.clear()
  6323. self.source_editor_tab.code_editor.setReadOnly(False)
  6324. self.source_editor_tab.code_editor.completer_enable = False
  6325. self.source_editor_tab.buttonRun.hide()
  6326. # Switch plot_area to CNCJob tab
  6327. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6328. try:
  6329. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6330. except TypeError:
  6331. pass
  6332. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6333. try:
  6334. self.source_editor_tab.buttonSave.clicked.disconnect()
  6335. except TypeError:
  6336. pass
  6337. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6338. # then append the text from GCode to the text editor
  6339. if obj.kind == 'cncjob':
  6340. try:
  6341. file = obj.export_gcode(
  6342. preamble=self.defaults["cncjob_prepend"],
  6343. postamble=self.defaults["cncjob_append"],
  6344. to_file=True)
  6345. if file == 'fail':
  6346. return 'fail'
  6347. except AttributeError:
  6348. self.inform.emit('[WARNING_NOTCL] %s' %
  6349. _("There is no selected object for which to see it's source file code."))
  6350. return 'fail'
  6351. else:
  6352. try:
  6353. file = StringIO(obj.source_file)
  6354. except (AttributeError, TypeError):
  6355. self.inform.emit('[WARNING_NOTCL] %s' %
  6356. _("There is no selected object for which to see it's source file code."))
  6357. return 'fail'
  6358. self.source_editor_tab.t_frame.hide()
  6359. try:
  6360. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6361. # for line in file:
  6362. # QtWidgets.QApplication.processEvents()
  6363. # proc_line = str(line).strip('\n')
  6364. # self.source_editor_tab.code_editor.append(proc_line)
  6365. except Exception as e:
  6366. log.debug('App.on_view_source() -->%s' % str(e))
  6367. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6368. return
  6369. self.source_editor_tab.handleTextChanged()
  6370. self.source_editor_tab.t_frame.show()
  6371. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6372. self.proc_container.view.set_idle()
  6373. # self.ui.show()
  6374. def on_toggle_code_editor(self):
  6375. self.defaults.report_usage("on_toggle_code_editor()")
  6376. if self.toggle_codeeditor is False:
  6377. self.init_code_editor(name=_("Code Editor"))
  6378. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6379. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6380. self.text_editor_tab.buttonSave.clicked.disconnect()
  6381. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6382. else:
  6383. for idx in range(self.ui.plot_tab_area.count()):
  6384. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6385. self.ui.plot_tab_area.closeTab(idx)
  6386. break
  6387. self.toggle_codeeditor = False
  6388. def on_code_editor_close(self):
  6389. self.toggle_codeeditor = False
  6390. def goto_text_line(self):
  6391. """
  6392. Will scroll a text to the specified text line.
  6393. :return: None
  6394. """
  6395. dia_box = Dialog_box(title=_("Go to Line ..."),
  6396. label=_("Line:"),
  6397. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6398. initial_text='')
  6399. try:
  6400. line = int(dia_box.location) - 1
  6401. except (ValueError, TypeError):
  6402. line = 0
  6403. if dia_box.ok:
  6404. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6405. # at the top of the window
  6406. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6407. # get the document() of the AppTextEditor
  6408. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6409. # create a Text Cursor based on the searched line
  6410. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6411. # set cursor of the code editor with the cursor at the searcehd line
  6412. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6413. def on_filenewscript(self, silent=False):
  6414. """
  6415. Will create a new script file and open it in the Code Editor
  6416. :param silent: if True will not display status messages
  6417. :return: None
  6418. """
  6419. if silent is False:
  6420. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6421. # delete the absolute and relative position and messages in the infobar
  6422. # self.ui.position_label.setText("")
  6423. # self.ui.rel_position_label.setText("")
  6424. # hide coordinates toolbars in the infobar while in DB
  6425. self.ui.coords_toolbar.hide()
  6426. self.ui.delta_coords_toolbar.hide()
  6427. self.app_obj.new_script_object()
  6428. # script_text = script_obj.source_file
  6429. #
  6430. # self.proc_container.view.set_busy(_("Loading..."))
  6431. # script_obj.script_editor_tab.t_frame.hide()
  6432. #
  6433. # script_obj.script_editor_tab.t_frame.show()
  6434. # self.proc_container.view.set_idle()
  6435. def on_fileopenscript(self, name=None, silent=False):
  6436. """
  6437. Will open a Tcl script file into the Code Editor
  6438. :param silent: if True will not display status messages
  6439. :param name: name of a Tcl script file to open
  6440. :return: None
  6441. """
  6442. self.defaults.report_usage("on_fileopenscript")
  6443. App.log.debug("on_fileopenscript()")
  6444. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6445. "All Files (*.*)"
  6446. if name:
  6447. filenames = [name]
  6448. else:
  6449. try:
  6450. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6451. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6452. except TypeError:
  6453. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6454. if len(filenames) == 0:
  6455. if silent is False:
  6456. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6457. else:
  6458. for filename in filenames:
  6459. if filename != '':
  6460. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6461. def on_fileopenscript_example(self, name=None, silent=False):
  6462. """
  6463. Will open a Tcl script file into the Code Editor
  6464. :param silent: if True will not display status messages
  6465. :param name: name of a Tcl script file to open
  6466. :return:
  6467. """
  6468. self.defaults.report_usage("on_fileopenscript_example")
  6469. log.debug("on_fileopenscript_example()")
  6470. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6471. "All Files (*.*)"
  6472. # test if the app was frozen and choose the path for the configuration file
  6473. if getattr(sys, "frozen", False) is True:
  6474. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6475. else:
  6476. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6477. if name:
  6478. filenames = [name]
  6479. else:
  6480. try:
  6481. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6482. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6483. except TypeError:
  6484. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6485. if len(filenames) == 0:
  6486. if silent is False:
  6487. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6488. else:
  6489. for filename in filenames:
  6490. if filename != '':
  6491. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6492. def on_filerunscript(self, name=None, silent=False):
  6493. """
  6494. File menu callback for loading and running a TCL script.
  6495. :param silent: if True will not display status messages
  6496. :param name: name of a Tcl script file to be run by FlatCAM
  6497. :return: None
  6498. """
  6499. self.defaults.report_usage("on_filerunscript")
  6500. App.log.debug("on_file_runscript()")
  6501. if name:
  6502. filename = name
  6503. if self.cmd_line_headless != 1:
  6504. self.splash.showMessage('%s: %ssec\n%s' %
  6505. (_("Canvas initialization started.\n"
  6506. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6507. _("Executing ScriptObject file.")
  6508. ),
  6509. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6510. color=QtGui.QColor("gray"))
  6511. else:
  6512. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6513. "All Files (*.*)"
  6514. try:
  6515. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6516. directory=self.get_last_folder(), filter=_filter_)
  6517. except TypeError:
  6518. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6519. # The Qt methods above will return a QString which can cause problems later.
  6520. # So far json.dump() will fail to serialize it.
  6521. filename = str(filename)
  6522. if filename == "":
  6523. if silent is False:
  6524. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6525. else:
  6526. if self.cmd_line_headless != 1:
  6527. if self.ui.shell_dock.isHidden():
  6528. self.ui.shell_dock.show()
  6529. try:
  6530. with open(filename, "r") as tcl_script:
  6531. cmd_line_shellfile_content = tcl_script.read()
  6532. if self.cmd_line_headless != 1:
  6533. self.shell.exec_command(cmd_line_shellfile_content)
  6534. else:
  6535. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6536. if silent is False:
  6537. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6538. except Exception as e:
  6539. log.debug("App.on_filerunscript() -> %s" % str(e))
  6540. sys.exit(2)
  6541. def on_file_saveproject(self, silent=False):
  6542. """
  6543. Callback for menu item File->Save Project. Saves the project to
  6544. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6545. if set to None. The project is saved by calling ``self.save_project()``.
  6546. :param silent: if True will not display status messages
  6547. :return: None
  6548. """
  6549. self.defaults.report_usage("on_file_saveproject")
  6550. if self.project_filename is None:
  6551. self.on_file_saveprojectas()
  6552. else:
  6553. self.worker_task.emit({'fcn': self.save_project,
  6554. 'params': [self.project_filename, silent]})
  6555. if self.defaults["global_open_style"] is False:
  6556. self.file_opened.emit("project", self.project_filename)
  6557. self.file_saved.emit("project", self.project_filename)
  6558. self.set_ui_title(name=self.project_filename)
  6559. self.should_we_save = False
  6560. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6561. """
  6562. Callback for menu item File->Save Project As... Opens a file
  6563. chooser and saves the project to the given file via
  6564. ``self.save_project()``.
  6565. :param make_copy if to be create a copy of the project; boolean
  6566. :param use_thread: if to be run in a separate thread; boolean
  6567. :param quit_action: if to be followed by quiting the application; boolean
  6568. :return: None
  6569. """
  6570. self.defaults.report_usage("on_file_saveprojectas")
  6571. self.date = str(datetime.today()).rpartition('.')[0]
  6572. self.date = ''.join(c for c in self.date if c not in ':-')
  6573. self.date = self.date.replace(' ', '_')
  6574. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6575. try:
  6576. filename, _f = FCFileSaveDialog.get_saved_filename(
  6577. caption=_("Save Project As ..."),
  6578. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6579. proj=_("Project")),
  6580. ext_filter=filter_
  6581. )
  6582. except TypeError:
  6583. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6584. filename = str(filename)
  6585. if filename == '':
  6586. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6587. return
  6588. if use_thread is True:
  6589. self.worker_task.emit({'fcn': self.save_project,
  6590. 'params': [filename, quit_action]})
  6591. else:
  6592. self.save_project(filename, quit_action)
  6593. # self.save_project(filename)
  6594. if self.defaults["global_open_style"] is False:
  6595. self.file_opened.emit("project", filename)
  6596. self.file_saved.emit("project", filename)
  6597. if not make_copy:
  6598. self.project_filename = filename
  6599. self.set_ui_title(name=self.project_filename)
  6600. self.should_we_save = False
  6601. def on_file_save_objects_pdf(self, use_thread=True):
  6602. self.date = str(datetime.today()).rpartition('.')[0]
  6603. self.date = ''.join(c for c in self.date if c not in ':-')
  6604. self.date = self.date.replace(' ', '_')
  6605. try:
  6606. obj_selection = self.collection.get_selected()
  6607. if len(obj_selection) == 1:
  6608. obj_name = str(obj_selection[0].options['name'])
  6609. else:
  6610. obj_name = _("FlatCAM objects print")
  6611. except AttributeError as err:
  6612. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6613. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6614. return
  6615. if not obj_selection:
  6616. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6617. return
  6618. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6619. try:
  6620. filename, _f = FCFileSaveDialog.get_saved_filename(
  6621. caption=_("Save Object as PDF ..."),
  6622. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6623. obj_name=obj_name,
  6624. date=self.date),
  6625. ext_filter=filter_
  6626. )
  6627. except TypeError:
  6628. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6629. filename = str(filename)
  6630. if filename == '':
  6631. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6632. return
  6633. if use_thread is True:
  6634. self.proc_container.new(_("Printing PDF ... Please wait."))
  6635. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6636. else:
  6637. self.save_pdf(filename, obj_selection)
  6638. # self.save_project(filename)
  6639. if self.defaults["global_open_style"] is False:
  6640. self.file_opened.emit("pdf", filename)
  6641. self.file_saved.emit("pdf", filename)
  6642. def save_pdf(self, file_name, obj_selection):
  6643. p_size = self.defaults['global_workspaceT']
  6644. orientation = self.defaults['global_workspace_orientation']
  6645. color = 'black'
  6646. transparency_level = 1.0
  6647. self.pagesize = {}
  6648. self.pagesize.update(
  6649. {
  6650. 'Bounds': None,
  6651. 'A0': (841 * mm, 1189 * mm),
  6652. 'A1': (594 * mm, 841 * mm),
  6653. 'A2': (420 * mm, 594 * mm),
  6654. 'A3': (297 * mm, 420 * mm),
  6655. 'A4': (210 * mm, 297 * mm),
  6656. 'A5': (148 * mm, 210 * mm),
  6657. 'A6': (105 * mm, 148 * mm),
  6658. 'A7': (74 * mm, 105 * mm),
  6659. 'A8': (52 * mm, 74 * mm),
  6660. 'A9': (37 * mm, 52 * mm),
  6661. 'A10': (26 * mm, 37 * mm),
  6662. 'B0': (1000 * mm, 1414 * mm),
  6663. 'B1': (707 * mm, 1000 * mm),
  6664. 'B2': (500 * mm, 707 * mm),
  6665. 'B3': (353 * mm, 500 * mm),
  6666. 'B4': (250 * mm, 353 * mm),
  6667. 'B5': (176 * mm, 250 * mm),
  6668. 'B6': (125 * mm, 176 * mm),
  6669. 'B7': (88 * mm, 125 * mm),
  6670. 'B8': (62 * mm, 88 * mm),
  6671. 'B9': (44 * mm, 62 * mm),
  6672. 'B10': (31 * mm, 44 * mm),
  6673. 'C0': (917 * mm, 1297 * mm),
  6674. 'C1': (648 * mm, 917 * mm),
  6675. 'C2': (458 * mm, 648 * mm),
  6676. 'C3': (324 * mm, 458 * mm),
  6677. 'C4': (229 * mm, 324 * mm),
  6678. 'C5': (162 * mm, 229 * mm),
  6679. 'C6': (114 * mm, 162 * mm),
  6680. 'C7': (81 * mm, 114 * mm),
  6681. 'C8': (57 * mm, 81 * mm),
  6682. 'C9': (40 * mm, 57 * mm),
  6683. 'C10': (28 * mm, 40 * mm),
  6684. # American paper sizes
  6685. 'LETTER': (8.5 * inch, 11 * inch),
  6686. 'LEGAL': (8.5 * inch, 14 * inch),
  6687. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6688. # From https://en.wikipedia.org/wiki/Paper_size
  6689. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6690. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6691. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6692. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6693. 'LEDGER': (17 * inch, 11 * inch),
  6694. }
  6695. )
  6696. exported_svg = []
  6697. for obj in obj_selection:
  6698. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6699. scale_factor_x=None, scale_factor_y=None,
  6700. skew_factor_x=None, skew_factor_y=None,
  6701. mirror=None)
  6702. if obj.kind.lower() == 'gerber':
  6703. # color = self.defaults["gerber_plot_fill"][:-2]
  6704. color = obj.fill_color[:-2]
  6705. elif obj.kind.lower() == 'excellon':
  6706. color = '#C40000'
  6707. elif obj.kind.lower() == 'geometry':
  6708. color = self.defaults["global_draw_color"]
  6709. # Change the attributes of the exported SVG
  6710. # We don't need stroke-width
  6711. # We set opacity to maximum
  6712. # We set the colour to WHITE
  6713. root = ET.fromstring(svg_obj)
  6714. for child in root:
  6715. child.set('fill', str(color))
  6716. child.set('opacity', str(transparency_level))
  6717. child.set('stroke', str(color))
  6718. exported_svg.append(ET.tostring(root))
  6719. xmin = Inf
  6720. ymin = Inf
  6721. xmax = -Inf
  6722. ymax = -Inf
  6723. for obj in obj_selection:
  6724. try:
  6725. gxmin, gymin, gxmax, gymax = obj.bounds()
  6726. xmin = min([xmin, gxmin])
  6727. ymin = min([ymin, gymin])
  6728. xmax = max([xmax, gxmax])
  6729. ymax = max([ymax, gymax])
  6730. except Exception as e:
  6731. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6732. # Determine bounding area for svg export
  6733. bounds = [xmin, ymin, xmax, ymax]
  6734. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6735. # This contain the measure units
  6736. uom = obj_selection[0].units.lower()
  6737. # Define a boundary around SVG of about 1.0mm (~39mils)
  6738. if uom in "mm":
  6739. boundary = 1.0
  6740. else:
  6741. boundary = 0.0393701
  6742. # Convert everything to strings for use in the xml doc
  6743. svgwidth = str(size[0] + (2 * boundary))
  6744. svgheight = str(size[1] + (2 * boundary))
  6745. minx = str(bounds[0] - boundary)
  6746. miny = str(bounds[1] + boundary + size[1])
  6747. # Add a SVG Header and footer to the svg output from shapely
  6748. # The transform flips the Y Axis so that everything renders
  6749. # properly within svg apps such as inkscape
  6750. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6751. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6752. svg_header += 'width="' + svgwidth + uom + '" '
  6753. svg_header += 'height="' + svgheight + uom + '" '
  6754. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6755. svg_header += '>'
  6756. svg_header += '<g transform="scale(1,-1)">'
  6757. svg_footer = '</g> </svg>'
  6758. svg_elem = str(svg_header)
  6759. for svg_item in exported_svg:
  6760. svg_elem += str(svg_item)
  6761. svg_elem += str(svg_footer)
  6762. # Parse the xml through a xml parser just to add line feeds
  6763. # and to make it look more pretty for the output
  6764. doc = parse_xml_string(svg_elem)
  6765. doc_final = doc.toprettyxml()
  6766. try:
  6767. if self.defaults['units'].upper() == 'IN':
  6768. unit = inch
  6769. else:
  6770. unit = mm
  6771. doc_final = StringIO(doc_final)
  6772. drawing = svg2rlg(doc_final)
  6773. if p_size == 'Bounds':
  6774. renderPDF.drawToFile(drawing, file_name)
  6775. else:
  6776. if orientation == 'p':
  6777. page_size = portrait(self.pagesize[p_size])
  6778. else:
  6779. page_size = landscape(self.pagesize[p_size])
  6780. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6781. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6782. renderPDF.draw(drawing, my_canvas, 0, 0)
  6783. my_canvas.save()
  6784. except Exception as e:
  6785. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6786. return 'fail'
  6787. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6788. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6789. """
  6790. Exports a Geometry Object to an SVG file.
  6791. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6792. :param filename: Path to the SVG file to save to.
  6793. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6794. :return:
  6795. """
  6796. self.defaults.report_usage("export_svg()")
  6797. if filename is None:
  6798. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6799. is not None else self.defaults["global_last_folder"]
  6800. self.log.debug("export_svg()")
  6801. try:
  6802. obj = self.collection.get_by_name(str(obj_name))
  6803. except Exception:
  6804. # TODO: The return behavior has not been established... should raise exception?
  6805. return "Could not retrieve object: %s" % obj_name
  6806. with self.proc_container.new(_("Exporting SVG")) as proc:
  6807. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6808. # Determine bounding area for svg export
  6809. bounds = obj.bounds()
  6810. size = obj.size()
  6811. # Convert everything to strings for use in the xml doc
  6812. svgwidth = str(size[0])
  6813. svgheight = str(size[1])
  6814. minx = str(bounds[0])
  6815. miny = str(bounds[1] - size[1])
  6816. uom = obj.units.lower()
  6817. # Add a SVG Header and footer to the svg output from shapely
  6818. # The transform flips the Y Axis so that everything renders
  6819. # properly within svg apps such as inkscape
  6820. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6821. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6822. svg_header += 'width="' + svgwidth + uom + '" '
  6823. svg_header += 'height="' + svgheight + uom + '" '
  6824. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6825. svg_header += '<g transform="scale(1,-1)">'
  6826. svg_footer = '</g> </svg>'
  6827. svg_elem = svg_header + exported_svg + svg_footer
  6828. # Parse the xml through a xml parser just to add line feeds
  6829. # and to make it look more pretty for the output
  6830. svgcode = parse_xml_string(svg_elem)
  6831. svgcode = svgcode.toprettyxml()
  6832. try:
  6833. with open(filename, 'w') as fp:
  6834. fp.write(svgcode)
  6835. except PermissionError:
  6836. self.inform.emit('[WARNING] %s' %
  6837. _("Permission denied, saving not possible.\n"
  6838. "Most likely another app is holding the file open and not accessible."))
  6839. return 'fail'
  6840. if self.defaults["global_open_style"] is False:
  6841. self.file_opened.emit("SVG", filename)
  6842. self.file_saved.emit("SVG", filename)
  6843. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6844. def save_source_file(self, obj_name, filename, use_thread=True):
  6845. """
  6846. Exports a FlatCAM Object to an Gerber/Excellon file.
  6847. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6848. :param filename: Path to the Gerber file to save to.
  6849. :param use_thread: if to be run in a separate thread
  6850. :return:
  6851. """
  6852. self.defaults.report_usage("save source file()")
  6853. if filename is None:
  6854. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6855. is not None else self.defaults["global_last_folder"]
  6856. self.log.debug("save source file()")
  6857. obj = self.collection.get_by_name(obj_name)
  6858. file_string = StringIO(obj.source_file)
  6859. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6860. if file_string.getvalue() == '':
  6861. self.inform.emit('[ERROR_NOTCL] %s' %
  6862. _("Save cancelled because source file is empty. Try to export the file."))
  6863. return 'fail'
  6864. try:
  6865. with open(filename, 'w') as file:
  6866. file.writelines('G04*\n')
  6867. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6868. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6869. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6870. file.writelines('G04 Created on : %s*\n' % time_string)
  6871. for line in file_string:
  6872. file.writelines(line)
  6873. except PermissionError:
  6874. self.inform.emit('[WARNING] %s' %
  6875. _("Permission denied, saving not possible.\n"
  6876. "Most likely another app is holding the file open and not accessible."))
  6877. return 'fail'
  6878. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6879. """
  6880. Exports a Excellon Object to an Excellon file.
  6881. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6882. :param filename: Path to the Excellon file to save to.
  6883. :param local_use:
  6884. :param use_thread: if to be run in a separate thread
  6885. :return:
  6886. """
  6887. self.defaults.report_usage("export_excellon()")
  6888. if filename is None:
  6889. if self.defaults["global_last_save_folder"]:
  6890. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6891. else:
  6892. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6893. self.log.debug("export_excellon()")
  6894. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6895. self.defaults["excellon_exp_decimals"]
  6896. )
  6897. if local_use is None:
  6898. try:
  6899. obj = self.collection.get_by_name(str(obj_name))
  6900. except Exception:
  6901. return "Could not retrieve object: %s" % obj_name
  6902. else:
  6903. obj = local_use
  6904. if not isinstance(obj, ExcellonObject):
  6905. self.inform.emit('[ERROR_NOTCL] %s' %
  6906. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6907. return
  6908. # updated units
  6909. eunits = self.defaults["excellon_exp_units"]
  6910. ewhole = self.defaults["excellon_exp_integer"]
  6911. efract = self.defaults["excellon_exp_decimals"]
  6912. ezeros = self.defaults["excellon_exp_zeros"]
  6913. eformat = self.defaults["excellon_exp_format"]
  6914. slot_type = self.defaults["excellon_exp_slot_type"]
  6915. fc_units = self.defaults['units'].upper()
  6916. if fc_units == 'MM':
  6917. factor = 1 if eunits == 'METRIC' else 0.03937
  6918. else:
  6919. factor = 25.4 if eunits == 'METRIC' else 1
  6920. def make_excellon():
  6921. try:
  6922. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6923. header = 'M48\n'
  6924. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6925. (str(self.version), str(self.version_date))
  6926. header += ';Filename: %s' % str(obj_name) + '\n'
  6927. header += ';Created on : %s' % time_str + '\n'
  6928. if eformat == 'dec':
  6929. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6930. header += eunits + '\n'
  6931. for tool in obj.tools:
  6932. if eunits == 'METRIC':
  6933. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6934. tool=str(tool),
  6935. dec=2)
  6936. else:
  6937. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6938. tool=str(tool),
  6939. dec=4)
  6940. else:
  6941. if ezeros == 'LZ':
  6942. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6943. form='ndec', e_zeros='LZ', factor=factor,
  6944. slot_type=slot_type)
  6945. header += '%s,%s\n' % (eunits, 'LZ')
  6946. header += format_exc
  6947. for tool in obj.tools:
  6948. if eunits == 'METRIC':
  6949. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6950. float(obj.tools[tool]['tooldia']) * factor,
  6951. tool=str(tool),
  6952. dec=2)
  6953. else:
  6954. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6955. float(obj.tools[tool]['tooldia']) * factor,
  6956. tool=str(tool),
  6957. dec=4)
  6958. else:
  6959. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6960. form='ndec', e_zeros='TZ', factor=factor,
  6961. slot_type=slot_type)
  6962. header += '%s,%s\n' % (eunits, 'TZ')
  6963. header += format_exc
  6964. for tool in obj.tools:
  6965. if eunits == 'METRIC':
  6966. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6967. float(obj.tools[tool]['tooldia']) * factor,
  6968. tool=str(tool),
  6969. dec=2)
  6970. else:
  6971. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6972. float(obj.tools[tool]['tooldia']) * factor,
  6973. tool=str(tool),
  6974. dec=4)
  6975. header += '%\n'
  6976. footer = 'M30\n'
  6977. exported_excellon = header
  6978. exported_excellon += excellon_code
  6979. exported_excellon += footer
  6980. if local_use is None:
  6981. try:
  6982. with open(filename, 'w') as fp:
  6983. fp.write(exported_excellon)
  6984. except PermissionError:
  6985. self.inform.emit('[WARNING] %s' %
  6986. _("Permission denied, saving not possible.\n"
  6987. "Most likely another app is holding the file open and not accessible."))
  6988. return 'fail'
  6989. if self.defaults["global_open_style"] is False:
  6990. self.file_opened.emit("Excellon", filename)
  6991. self.file_saved.emit("Excellon", filename)
  6992. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6993. else:
  6994. return exported_excellon
  6995. except Exception as e:
  6996. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6997. return 'fail'
  6998. if use_thread is True:
  6999. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7000. def job_thread_exc(app_obj):
  7001. ret = make_excellon()
  7002. if ret == 'fail':
  7003. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7004. return
  7005. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7006. else:
  7007. eret = make_excellon()
  7008. if eret == 'fail':
  7009. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7010. return 'fail'
  7011. if local_use is not None:
  7012. return eret
  7013. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7014. """
  7015. Exports a Gerber Object to an Gerber file.
  7016. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7017. :param filename: Path to the Gerber file to save to.
  7018. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7019. When not None, the value will be the actual Gerber object for which to create
  7020. the Gerber code
  7021. :param use_thread: if to be run in a separate thread
  7022. :return:
  7023. """
  7024. self.defaults.report_usage("export_gerber()")
  7025. if filename is None:
  7026. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7027. is not None else self.defaults["global_last_folder"]
  7028. self.log.debug("export_gerber()")
  7029. if local_use is None:
  7030. try:
  7031. obj = self.collection.get_by_name(str(obj_name))
  7032. except Exception:
  7033. return 'fail'
  7034. else:
  7035. obj = local_use
  7036. # updated units
  7037. gunits = self.defaults["gerber_exp_units"]
  7038. gwhole = self.defaults["gerber_exp_integer"]
  7039. gfract = self.defaults["gerber_exp_decimals"]
  7040. gzeros = self.defaults["gerber_exp_zeros"]
  7041. fc_units = self.defaults['units'].upper()
  7042. if fc_units == 'MM':
  7043. factor = 1 if gunits == 'MM' else 0.03937
  7044. else:
  7045. factor = 25.4 if gunits == 'MM' else 1
  7046. def make_gerber():
  7047. try:
  7048. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7049. header = 'G04*\n'
  7050. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7051. (str(self.version), str(self.version_date))
  7052. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7053. header += 'G04 Created on : %s*' % time_str + '\n'
  7054. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7055. header += "%MO{units}*%\n".format(units=gunits)
  7056. for apid in obj.apertures:
  7057. if obj.apertures[apid]['type'] == 'C':
  7058. header += "%ADD{apid}{type},{size}*%\n".format(
  7059. apid=str(apid),
  7060. type='C',
  7061. size=(factor * obj.apertures[apid]['size'])
  7062. )
  7063. elif obj.apertures[apid]['type'] == 'R':
  7064. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7065. apid=str(apid),
  7066. type='R',
  7067. width=(factor * obj.apertures[apid]['width']),
  7068. height=(factor * obj.apertures[apid]['height'])
  7069. )
  7070. elif obj.apertures[apid]['type'] == 'O':
  7071. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7072. apid=str(apid),
  7073. type='O',
  7074. width=(factor * obj.apertures[apid]['width']),
  7075. height=(factor * obj.apertures[apid]['height'])
  7076. )
  7077. header += '\n'
  7078. # obsolete units but some software may need it
  7079. if gunits == 'IN':
  7080. header += 'G70*\n'
  7081. else:
  7082. header += 'G71*\n'
  7083. # Absolute Mode
  7084. header += 'G90*\n'
  7085. header += 'G01*\n'
  7086. # positive polarity
  7087. header += '%LPD*%\n'
  7088. footer = 'M02*\n'
  7089. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7090. exported_gerber = header
  7091. exported_gerber += gerber_code
  7092. exported_gerber += footer
  7093. if local_use is None:
  7094. try:
  7095. with open(filename, 'w') as fp:
  7096. fp.write(exported_gerber)
  7097. except PermissionError:
  7098. self.inform.emit('[WARNING] %s' %
  7099. _("Permission denied, saving not possible.\n"
  7100. "Most likely another app is holding the file open and not accessible."))
  7101. return 'fail'
  7102. if self.defaults["global_open_style"] is False:
  7103. self.file_opened.emit("Gerber", filename)
  7104. self.file_saved.emit("Gerber", filename)
  7105. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7106. else:
  7107. return exported_gerber
  7108. except Exception as e:
  7109. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7110. return 'fail'
  7111. if use_thread is True:
  7112. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7113. def job_thread_grb(app_obj):
  7114. ret = make_gerber()
  7115. if ret == 'fail':
  7116. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7117. return
  7118. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7119. else:
  7120. gret = make_gerber()
  7121. if gret == 'fail':
  7122. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7123. return 'fail'
  7124. if local_use is not None:
  7125. return gret
  7126. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  7127. """
  7128. Exports a Geometry Object to an DXF file.
  7129. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7130. :param filename: Path to the DXF file to save to.
  7131. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7132. When not None, the value will be the actual Geometry object for which to create
  7133. the Geometry/DXF code
  7134. :param use_thread: if to be run in a separate thread
  7135. :return:
  7136. """
  7137. self.defaults.report_usage("export_dxf()")
  7138. if filename is None:
  7139. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7140. is not None else self.defaults["global_last_folder"]
  7141. self.log.debug("export_dxf()")
  7142. if local_use is None:
  7143. try:
  7144. obj = self.collection.get_by_name(str(obj_name))
  7145. except Exception:
  7146. return 'fail'
  7147. else:
  7148. obj = local_use
  7149. def make_dxf():
  7150. try:
  7151. dxf_code = obj.export_dxf()
  7152. if local_use is None:
  7153. try:
  7154. dxf_code.saveas(filename)
  7155. except PermissionError:
  7156. self.inform.emit('[WARNING] %s' %
  7157. _("Permission denied, saving not possible.\n"
  7158. "Most likely another app is holding the file open and not accessible."))
  7159. return 'fail'
  7160. if self.defaults["global_open_style"] is False:
  7161. self.file_opened.emit("DXF", filename)
  7162. self.file_saved.emit("DXF", filename)
  7163. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7164. else:
  7165. return dxf_code
  7166. except Exception as e:
  7167. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  7168. return 'fail'
  7169. if use_thread is True:
  7170. with self.proc_container.new(_("Exporting DXF")) as proc:
  7171. def job_thread_exc(app_obj):
  7172. ret_dxf_val = make_dxf()
  7173. if ret_dxf_val == 'fail':
  7174. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7175. return
  7176. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7177. else:
  7178. ret = make_dxf()
  7179. if ret == 'fail':
  7180. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7181. return
  7182. if local_use is not None:
  7183. return ret
  7184. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7185. """
  7186. Adds a new Geometry Object to the projects and populates
  7187. it with shapes extracted from the SVG file.
  7188. :param plot: If True then the resulting object will be plotted on canvas
  7189. :param filename: Path to the SVG file.
  7190. :param geo_type: Type of FlatCAM object that will be created from SVG
  7191. :param outname: The name given to the resulting FlatCAM object
  7192. :return:
  7193. """
  7194. self.defaults.report_usage("import_svg()")
  7195. log.debug("App.import_svg()")
  7196. obj_type = ""
  7197. if geo_type is None or geo_type == "geometry":
  7198. obj_type = "geometry"
  7199. elif geo_type == "gerber":
  7200. obj_type = "gerber"
  7201. else:
  7202. self.inform.emit('[ERROR_NOTCL] %s' %
  7203. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7204. return
  7205. units = self.defaults['units'].upper()
  7206. def obj_init(geo_obj, app_obj):
  7207. geo_obj.import_svg(filename, obj_type, units=units)
  7208. geo_obj.multigeo = False
  7209. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7210. with self.proc_container.new(_("Importing SVG")) as proc:
  7211. # Object name
  7212. name = outname or filename.split('/')[-1].split('\\')[-1]
  7213. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7214. if ret == 'fail':
  7215. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7216. return 'fail'
  7217. # Register recent file
  7218. self.file_opened.emit("svg", filename)
  7219. # appGUI feedback
  7220. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7221. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7222. """
  7223. Adds a new Geometry Object to the projects and populates
  7224. it with shapes extracted from the DXF file.
  7225. :param filename: Path to the DXF file.
  7226. :param geo_type: Type of FlatCAM object that will be created from DXF
  7227. :param outname: Name for the imported Geometry
  7228. :param plot: If True then the resulting object will be plotted on canvas
  7229. :return:
  7230. """
  7231. log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  7232. obj_type = ""
  7233. if geo_type is None or geo_type == "geometry":
  7234. obj_type = "geometry"
  7235. elif geo_type == "gerber":
  7236. obj_type = geo_type
  7237. else:
  7238. self.inform.emit('[ERROR_NOTCL] %s' %
  7239. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7240. return
  7241. units = self.defaults['units'].upper()
  7242. def obj_init(geo_obj, app_obj):
  7243. if obj_type == "geometry":
  7244. geo_obj.import_dxf_as_geo(filename, units=units)
  7245. elif obj_type == "gerber":
  7246. geo_obj.import_dxf_as_gerber(filename, units=units)
  7247. else:
  7248. return "fail"
  7249. geo_obj.multigeo = True
  7250. with self.proc_container.new(_("Importing DXF")):
  7251. # Object name
  7252. name = outname or filename.split('/')[-1].split('\\')[-1]
  7253. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7254. if ret == 'fail':
  7255. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7256. return 'fail'
  7257. # Register recent file
  7258. self.file_opened.emit("dxf", filename)
  7259. # appGUI feedback
  7260. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7261. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7262. """
  7263. Opens a Gerber file, parses it and creates a new object for
  7264. it in the program. Thread-safe.
  7265. :param outname: Name of the resulting object. None causes the
  7266. name to be that of the file. Str.
  7267. :param filename: Gerber file filename
  7268. :type filename: str
  7269. :param plot: boolean, to plot or not the resulting object
  7270. :param from_tcl: True if run from Tcl Shell
  7271. :return: None
  7272. """
  7273. # How the object should be initialized
  7274. def obj_init(gerber_obj, app_obj):
  7275. assert isinstance(gerber_obj, GerberObject), \
  7276. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7277. # Opening the file happens here
  7278. try:
  7279. gerber_obj.parse_file(filename)
  7280. except IOError:
  7281. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7282. return "fail"
  7283. except ParseError as err:
  7284. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7285. app_obj.log.error(str(err))
  7286. return "fail"
  7287. except Exception as e:
  7288. log.debug("App.open_gerber() --> %s" % str(e))
  7289. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7290. msg += traceback.format_exc()
  7291. app_obj.inform.emit(msg)
  7292. return "fail"
  7293. if gerber_obj.is_empty():
  7294. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7295. _("Object is not Gerber file or empty. Aborting object creation."))
  7296. return "fail"
  7297. App.log.debug("open_gerber()")
  7298. with self.proc_container.new(_("Opening Gerber")):
  7299. # Object name
  7300. name = outname or filename.split('/')[-1].split('\\')[-1]
  7301. # # ## Object creation # ##
  7302. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7303. if ret_val == 'fail':
  7304. if from_tcl:
  7305. filename = self.defaults['global_tcl_path'] + '/' + name
  7306. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7307. if ret_val == 'fail':
  7308. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7309. return 'fail'
  7310. # Register recent file
  7311. self.file_opened.emit("gerber", filename)
  7312. # appGUI feedback
  7313. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7314. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7315. """
  7316. Opens an Excellon file, parses it and creates a new object for
  7317. it in the program. Thread-safe.
  7318. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7319. :param filename: Excellon file filename
  7320. :type filename: str
  7321. :param plot: boolean, to plot or not the resulting object
  7322. :param from_tcl: True if run from Tcl Shell
  7323. :return: None
  7324. """
  7325. App.log.debug("open_excellon()")
  7326. # How the object should be initialized
  7327. def obj_init(excellon_obj, app_obj):
  7328. try:
  7329. ret = excellon_obj.parse_file(filename=filename)
  7330. if ret == "fail":
  7331. log.debug("Excellon parsing failed.")
  7332. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  7333. return "fail"
  7334. except IOError:
  7335. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  7336. log.debug("Could not open Excellon object.")
  7337. return "fail"
  7338. except Exception:
  7339. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7340. msg += traceback.format_exc()
  7341. app_obj.inform.emit(msg)
  7342. return "fail"
  7343. ret = excellon_obj.create_geometry()
  7344. if ret == 'fail':
  7345. log.debug("Could not create geometry for Excellon object.")
  7346. return "fail"
  7347. for tool in excellon_obj.tools:
  7348. if excellon_obj.tools[tool]['solid_geometry']:
  7349. return
  7350. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7351. return "fail"
  7352. with self.proc_container.new(_("Opening Excellon.")):
  7353. # Object name
  7354. name = outname or filename.split('/')[-1].split('\\')[-1]
  7355. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7356. if ret_val == 'fail':
  7357. if from_tcl:
  7358. filename = self.defaults['global_tcl_path'] + '/' + name
  7359. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7360. if ret_val == 'fail':
  7361. self.inform.emit('[ERROR_NOTCL] %s' %
  7362. _('Open Excellon file failed. Probable not an Excellon file.'))
  7363. return
  7364. # Register recent file
  7365. self.file_opened.emit("excellon", filename)
  7366. # appGUI feedback
  7367. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7368. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7369. """
  7370. Opens a G-gcode file, parses it and creates a new object for
  7371. it in the program. Thread-safe.
  7372. :param filename: G-code file filename
  7373. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7374. :param force_parsing:
  7375. :param plot: If True plot the object on canvas
  7376. :param from_tcl: True if run from Tcl Shell
  7377. :return: None
  7378. """
  7379. App.log.debug("open_gcode()")
  7380. # How the object should be initialized
  7381. def obj_init(job_obj, app_obj_):
  7382. """
  7383. :param job_obj: the resulting object
  7384. :type app_obj_: App
  7385. """
  7386. assert isinstance(app_obj_, App), \
  7387. "Initializer expected App, got %s" % type(app_obj_)
  7388. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7389. try:
  7390. f = open(filename)
  7391. gcode = f.read()
  7392. f.close()
  7393. except IOError:
  7394. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7395. return "fail"
  7396. job_obj.gcode = gcode
  7397. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7398. if gcode_ret == "fail":
  7399. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7400. return "fail"
  7401. job_obj.create_geometry()
  7402. with self.proc_container.new(_("Opening G-Code.")):
  7403. # Object name
  7404. name = outname or filename.split('/')[-1].split('\\')[-1]
  7405. # New object creation and file processing
  7406. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7407. if ret_val == 'fail':
  7408. if from_tcl:
  7409. filename = self.defaults['global_tcl_path'] + '/' + name
  7410. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7411. if ret_val == 'fail':
  7412. self.inform.emit('[ERROR_NOTCL] %s' %
  7413. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7414. "Try to load it from File menu.\n "
  7415. "Attempting to create a FlatCAM CNCJob Object from "
  7416. "G-Code file failed during processing"))
  7417. return "fail"
  7418. # Register recent file
  7419. self.file_opened.emit("cncjob", filename)
  7420. # appGUI feedback
  7421. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7422. def open_hpgl2(self, filename, outname=None):
  7423. """
  7424. Opens a HPGL2 file, parses it and creates a new object for
  7425. it in the program. Thread-safe.
  7426. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7427. :param filename: HPGL2 file filename
  7428. :return: None
  7429. """
  7430. filename = filename
  7431. # How the object should be initialized
  7432. def obj_init(geo_obj, app_obj):
  7433. assert isinstance(geo_obj, GeometryObject), \
  7434. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7435. # Opening the file happens here
  7436. obj = HPGL2(self)
  7437. try:
  7438. HPGL2.parse_file(obj, filename)
  7439. except IOError:
  7440. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7441. return "fail"
  7442. except ParseError as err:
  7443. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7444. app_obj.log.error(str(err))
  7445. return "fail"
  7446. except Exception as e:
  7447. log.debug("App.open_hpgl2() --> %s" % str(e))
  7448. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7449. msg += traceback.format_exc()
  7450. app_obj.inform.emit(msg)
  7451. return "fail"
  7452. geo_obj.multigeo = True
  7453. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7454. geo_obj.tools = deepcopy(obj.tools)
  7455. geo_obj.source_file = deepcopy(obj.source_file)
  7456. del obj
  7457. if not geo_obj.solid_geometry:
  7458. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7459. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7460. return "fail"
  7461. App.log.debug("open_hpgl2()")
  7462. with self.proc_container.new(_("Opening HPGL2")):
  7463. # Object name
  7464. name = outname or filename.split('/')[-1].split('\\')[-1]
  7465. # # ## Object creation # ##
  7466. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7467. if ret == 'fail':
  7468. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7469. return 'fail'
  7470. # Register recent file
  7471. self.file_opened.emit("geometry", filename)
  7472. # appGUI feedback
  7473. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7474. def open_script(self, filename, outname=None, silent=False):
  7475. """
  7476. Opens a Script file, parses it and creates a new object for
  7477. it in the program. Thread-safe.
  7478. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7479. :param filename: Script file filename
  7480. :param silent: If True there will be no messages printed to StatusBar
  7481. :return: None
  7482. """
  7483. def obj_init(script_obj, app_obj):
  7484. assert isinstance(script_obj, ScriptObject), \
  7485. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7486. if silent is False:
  7487. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7488. try:
  7489. script_obj.parse_file(filename)
  7490. except IOError:
  7491. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7492. return "fail"
  7493. except ParseError as err:
  7494. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7495. app_obj.log.error(str(err))
  7496. return "fail"
  7497. except Exception as e:
  7498. log.debug("App.open_script() -> %s" % str(e))
  7499. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7500. msg += traceback.format_exc()
  7501. app_obj.inform.emit(msg)
  7502. return "fail"
  7503. App.log.debug("open_script()")
  7504. with self.proc_container.new(_("Opening TCL Script...")):
  7505. # Object name
  7506. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7507. # Object creation
  7508. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7509. if ret_val == 'fail':
  7510. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7511. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7512. if ret_val == 'fail':
  7513. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7514. return 'fail'
  7515. # Register recent file
  7516. self.file_opened.emit("script", filename)
  7517. # appGUI feedback
  7518. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7519. def open_config_file(self, filename, run_from_arg=None):
  7520. """
  7521. Loads a config file from the specified file.
  7522. :param filename: Name of the file from which to load.
  7523. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7524. :return: None
  7525. """
  7526. App.log.debug("Opening config file: " + filename)
  7527. if run_from_arg:
  7528. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7529. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7530. _("Opening FlatCAM Config file.")),
  7531. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7532. color=QtGui.QColor("gray"))
  7533. # # add the tab if it was closed
  7534. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7535. # # first clear previous text in text editor (if any)
  7536. # self.ui.text_editor_tab.code_editor.clear()
  7537. #
  7538. # # Switch plot_area to CNCJob tab
  7539. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7540. # close the Code editor if already open
  7541. if self.toggle_codeeditor:
  7542. self.on_toggle_code_editor()
  7543. self.on_toggle_code_editor()
  7544. try:
  7545. if filename:
  7546. f = QtCore.QFile(filename)
  7547. if f.open(QtCore.QIODevice.ReadOnly):
  7548. stream = QtCore.QTextStream(f)
  7549. code_edited = stream.readAll()
  7550. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7551. f.close()
  7552. except IOError:
  7553. App.log.error("Failed to open config file: %s" % filename)
  7554. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7555. (_("Failed to open config file"), filename))
  7556. return
  7557. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7558. """
  7559. Loads a project from the specified file.
  7560. 1) Loads and parses file
  7561. 2) Registers the file as recently opened.
  7562. 3) Calls on_file_new()
  7563. 4) Updates options
  7564. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7565. 6) Calls plot_all() if plot=True
  7566. :param filename: Name of the file from which to load.
  7567. :param run_from_arg: True if run for arguments
  7568. :param plot: If True plot all objects in the project
  7569. :param cli: Run from command line
  7570. :param from_tcl: True if run from Tcl Sehll
  7571. :return: None
  7572. """
  7573. App.log.debug("Opening project: " + filename)
  7574. # block autosaving while a project is loaded
  7575. self.block_autosave = True
  7576. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7577. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7578. if cli is None:
  7579. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7580. if run_from_arg:
  7581. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7582. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7583. _("Opening FlatCAM Project file.")),
  7584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7585. color=QtGui.QColor("gray"))
  7586. # Open and parse an uncompressed Project file
  7587. try:
  7588. f = open(filename, 'r')
  7589. except IOError:
  7590. if from_tcl:
  7591. name = filename.split('/')[-1].split('\\')[-1]
  7592. filename = self.defaults['global_tcl_path'] + '/' + name
  7593. try:
  7594. f = open(filename, 'r')
  7595. except IOError:
  7596. log.error("Failed to open project file: %s" % filename)
  7597. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7598. return
  7599. else:
  7600. log.error("Failed to open project file: %s" % filename)
  7601. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7602. return
  7603. try:
  7604. d = json.load(f, object_hook=dict2obj)
  7605. except Exception as e:
  7606. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7607. (filename, str(e)))
  7608. f.close()
  7609. # Open and parse a compressed Project file
  7610. try:
  7611. with lzma.open(filename) as f:
  7612. file_content = f.read().decode('utf-8')
  7613. d = json.loads(file_content, object_hook=dict2obj)
  7614. except Exception as e:
  7615. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7616. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7617. return
  7618. # Clear the current project
  7619. # # NOT THREAD SAFE # ##
  7620. if run_from_arg is True:
  7621. pass
  7622. elif cli is True:
  7623. self.delete_selection_shape()
  7624. else:
  7625. self.on_file_new()
  7626. # Project options
  7627. self.options.update(d['options'])
  7628. self.project_filename = filename
  7629. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7630. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7631. if cli is None:
  7632. self.set_screen_units(self.options["units"])
  7633. # Re create objects
  7634. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7635. for obj in d['objs']:
  7636. def obj_init(obj_inst, app_inst):
  7637. try:
  7638. obj_inst.from_dict(obj)
  7639. except Exception as e:
  7640. print('App.open_project() --> ' + str(e))
  7641. return 'fail'
  7642. App.log.debug("Recreating from opened project an %s object: %s" %
  7643. (obj['kind'].capitalize(), obj['options']['name']))
  7644. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7645. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7646. if cli is None:
  7647. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7648. obj['kind'].upper(),
  7649. obj['options']['name']
  7650. )
  7651. )
  7652. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7653. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7654. self.should_we_save = False
  7655. self.file_opened.emit("project", filename)
  7656. # restore autosaving after a project was loaded
  7657. self.block_autosave = False
  7658. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7659. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7660. if cli is None:
  7661. self.set_ui_title(name=self.project_filename)
  7662. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7663. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7664. """
  7665. Re-generates all plots from all objects.
  7666. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7667. :param muted: if True don't print messages
  7668. :param use_thread: if True will use threading for plotting the objects
  7669. :return: None
  7670. """
  7671. self.log.debug("Plot_all()")
  7672. if muted is not True:
  7673. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7674. for plot_obj in self.collection.get_list():
  7675. def worker_task(obj):
  7676. with self.proc_container.new("Plotting"):
  7677. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7678. if fit_view is True:
  7679. self.app_obj.object_plotted.emit(obj)
  7680. if use_thread is True:
  7681. # Send to worker
  7682. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7683. else:
  7684. worker_task(plot_obj)
  7685. def register_folder(self, filename):
  7686. """
  7687. Register the last folder used by the app to open something
  7688. :param filename: the last folder is extracted from the filename
  7689. :return: None
  7690. """
  7691. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7692. def register_save_folder(self, filename):
  7693. """
  7694. Register the last folder used by the app to save something
  7695. :param filename: the last folder is extracted from the filename
  7696. :return: None
  7697. """
  7698. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7699. # def set_progress_bar(self, percentage, text=""):
  7700. # """
  7701. # Set a progress bar to a value (percentage)
  7702. #
  7703. # :param percentage: Value set to the progressbar
  7704. # :param text: Not used
  7705. # :return: None
  7706. # """
  7707. # self.ui.progress_bar.setValue(int(percentage))
  7708. def setup_recent_items(self):
  7709. """
  7710. Setup a dictionary with the recent files accessed, organized by type
  7711. :return:
  7712. """
  7713. icons = {
  7714. "gerber": self.resource_location + "/flatcam_icon16.png",
  7715. "excellon": self.resource_location + "/drill16.png",
  7716. 'geometry': self.resource_location + "/geometry16.png",
  7717. "cncjob": self.resource_location + "/cnc16.png",
  7718. "script": self.resource_location + "/script_new24.png",
  7719. "document": self.resource_location + "/notes16_1.png",
  7720. "project": self.resource_location + "/project16.png",
  7721. "svg": self.resource_location + "/geometry16.png",
  7722. "dxf": self.resource_location + "/dxf16.png",
  7723. "pdf": self.resource_location + "/pdf32.png",
  7724. "image": self.resource_location + "/image16.png"
  7725. }
  7726. try:
  7727. image_opener = self.image_tool.import_image
  7728. except AttributeError:
  7729. image_opener = None
  7730. openers = {
  7731. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7732. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7733. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7734. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7735. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7736. "document": None,
  7737. 'project': self.open_project,
  7738. 'svg': self.import_svg,
  7739. 'dxf': self.import_dxf,
  7740. 'image': image_opener,
  7741. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7742. }
  7743. # Open recent file for files
  7744. try:
  7745. f = open(self.data_path + '/recent.json')
  7746. except IOError:
  7747. App.log.error("Failed to load recent item list.")
  7748. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7749. return
  7750. try:
  7751. self.recent = json.load(f)
  7752. except json.errors.JSONDecodeError:
  7753. App.log.error("Failed to parse recent item list.")
  7754. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7755. f.close()
  7756. return
  7757. f.close()
  7758. # Open recent file for projects
  7759. try:
  7760. fp = open(self.data_path + '/recent_projects.json')
  7761. except IOError:
  7762. App.log.error("Failed to load recent project item list.")
  7763. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7764. return
  7765. try:
  7766. self.recent_projects = json.load(fp)
  7767. except json.errors.JSONDecodeError:
  7768. App.log.error("Failed to parse recent project item list.")
  7769. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7770. fp.close()
  7771. return
  7772. fp.close()
  7773. # Closure needed to create callbacks in a loop.
  7774. # Otherwise late binding occurs.
  7775. def make_callback(func, fname):
  7776. def opener():
  7777. func(fname)
  7778. return opener
  7779. def reset_recent_files():
  7780. # Reset menu
  7781. self.ui.recent.clear()
  7782. self.recent = []
  7783. try:
  7784. ff = open(self.data_path + '/recent.json', 'w')
  7785. except IOError:
  7786. App.log.error("Failed to open recent items file for writing.")
  7787. return
  7788. json.dump(self.recent, ff)
  7789. def reset_recent_projects():
  7790. # Reset menu
  7791. self.ui.recent_projects.clear()
  7792. self.recent_projects = []
  7793. try:
  7794. frp = open(self.data_path + '/recent_projects.json', 'w')
  7795. except IOError:
  7796. App.log.error("Failed to open recent projects items file for writing.")
  7797. return
  7798. json.dump(self.recent, frp)
  7799. # Reset menu
  7800. self.ui.recent.clear()
  7801. self.ui.recent_projects.clear()
  7802. # Create menu items for projects
  7803. for recent in self.recent_projects:
  7804. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7805. if recent['kind'] == 'project':
  7806. try:
  7807. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7808. # Attach callback
  7809. o = make_callback(openers[recent["kind"]], recent['filename'])
  7810. action.triggered.connect(o)
  7811. self.ui.recent_projects.addAction(action)
  7812. except KeyError:
  7813. App.log.error("Unsupported file type: %s" % recent["kind"])
  7814. # Last action in Recent Files menu is one that Clear the content
  7815. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7816. (_("Clear Recent projects")), self)
  7817. clear_action_proj.triggered.connect(reset_recent_projects)
  7818. self.ui.recent_projects.addSeparator()
  7819. self.ui.recent_projects.addAction(clear_action_proj)
  7820. # Create menu items for files
  7821. for recent in self.recent:
  7822. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7823. if recent['kind'] != 'project':
  7824. try:
  7825. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7826. # Attach callback
  7827. o = make_callback(openers[recent["kind"]], recent['filename'])
  7828. action.triggered.connect(o)
  7829. self.ui.recent.addAction(action)
  7830. except KeyError:
  7831. App.log.error("Unsupported file type: %s" % recent["kind"])
  7832. # Last action in Recent Files menu is one that Clear the content
  7833. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7834. (_("Clear Recent files")), self)
  7835. clear_action.triggered.connect(reset_recent_files)
  7836. self.ui.recent.addSeparator()
  7837. self.ui.recent.addAction(clear_action)
  7838. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7839. # self.ui.menufilerecent.set_submenu(recent_menu)
  7840. # recent_menu.show_all()
  7841. # self.ui.recent.show()
  7842. self.log.debug("Recent items list has been populated.")
  7843. def setup_component_editor(self):
  7844. """
  7845. Default text for the Selected tab when is not taken by the Object UI.
  7846. :return:
  7847. """
  7848. # label = QtWidgets.QLabel("Choose an item from Project")
  7849. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7850. sel_title = QtWidgets.QTextEdit(
  7851. _('<b>Shortcut Key List</b>'))
  7852. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7853. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7854. f_settings = QSettings("Open Source", "FlatCAM")
  7855. if f_settings.contains("notebook_font_size"):
  7856. fsize = f_settings.value('notebook_font_size', type=int)
  7857. else:
  7858. fsize = 12
  7859. tsize = fsize + int(fsize / 2)
  7860. # selected_text = (_('''
  7861. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7862. # </p>
  7863. #
  7864. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7865. # The normal flow when working in FlatCAM is the following:</span></p>
  7866. #
  7867. # <ol>
  7868. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7869. # file into
  7870. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7871. # even dragging and dropping the files on the appGUI.<br />
  7872. # <br />
  7873. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7874. # drop of the
  7875. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7876. # &nbsp;</li>
  7877. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7878. # and then
  7879. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7880. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7881. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7882. # <br />
  7883. # If the selection of the object is done on the canvas by single click instead, and the
  7884. # <strong>SELECTED TAB</strong>
  7885. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7886. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7887. # it even if it was out of focus.<br />
  7888. # <br />
  7889. # You can change the parameters in this screen and the flow direction is like this:<br />
  7890. # <br />
  7891. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7892. # <strong> Geometry Object
  7893. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7894. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7895. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7896. # </ol>
  7897. #
  7898. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7899. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7900. # <strong>F3</strong>.</span></p>
  7901. #
  7902. # ''').format(fsize=fsize, tsize=tsize))
  7903. selected_text = '''
  7904. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7905. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7906. {s1}</span></p>
  7907. <ol>
  7908. <li><span style="font-size:{fsize}px">{s2}<br />
  7909. <br />
  7910. {s3}</span><br />
  7911. &nbsp;</li>
  7912. <li><span style="font-size:{fsize}px">{s4}<br />
  7913. &nbsp;</li>
  7914. <br />
  7915. <li><span style="font-size:{fsize}px">{s5}<br />
  7916. &nbsp;</li>
  7917. <br />
  7918. <li><span style="font-size:{fsize}px">{s6}<br />
  7919. <br />
  7920. {s7}</span></li>
  7921. </ol>
  7922. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7923. '''.format(
  7924. title=_("Selected Tab - Choose an Item from Project Tab"),
  7925. subtitle=_("Details"),
  7926. s1=_("The normal flow when working with the application is the following:"),
  7927. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7928. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7929. "files on the GUI."),
  7930. s3=_("You can also load a project by double clicking on the project file, "
  7931. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7932. "actions offered within the app."),
  7933. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7934. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7935. "SELECTED TAB will be updated with the object properties according to its kind: "
  7936. "Gerber, Excellon, Geometry or CNCJob object."),
  7937. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7938. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7939. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7940. "the SELECTED TAB and populate it even if it was out of focus."),
  7941. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7942. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7943. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7944. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7945. "(again, done in SELECTED TAB) --> Save GCode."),
  7946. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7947. "or through its own key shortcut: <b>F3</b>."),
  7948. tsize=tsize,
  7949. fsize=fsize
  7950. )
  7951. sel_title.setText(selected_text)
  7952. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7953. self.ui.selected_scroll_area.setWidget(sel_title)
  7954. def setup_obj_classes(self):
  7955. """
  7956. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7957. class.
  7958. :return: None
  7959. """
  7960. FlatCAMObj.app = self
  7961. ObjectCollection.app = self
  7962. Gerber.app = self
  7963. Excellon.app = self
  7964. Geometry.app = self
  7965. CNCjob.app = self
  7966. FCProcess.app = self
  7967. FCProcessContainer.app = self
  7968. OptionsGroupUI.app = self
  7969. def version_check(self):
  7970. """
  7971. Checks for the latest version of the program. Alerts the
  7972. user if theirs is outdated. This method is meant to be run
  7973. in a separate thread.
  7974. :return: None
  7975. """
  7976. self.log.debug("version_check()")
  7977. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7978. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7979. App.version_url,
  7980. str(self.defaults['global_serial']),
  7981. str(self.version),
  7982. str(self.os),
  7983. urllib.parse.urlencode(self.defaults["global_stats"])
  7984. )
  7985. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7986. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7987. # urllib.parse.urlencode(self.defaults["global_stats"])
  7988. else:
  7989. # no_stats dict; just so it won't break things on website
  7990. no_ststs_dict = {}
  7991. no_ststs_dict["global_ststs"] = {}
  7992. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7993. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7994. App.log.debug("Checking for updates @ %s" % full_url)
  7995. # ## Get the data
  7996. try:
  7997. f = urllib.request.urlopen(full_url)
  7998. except Exception:
  7999. # App.log.warning("Failed checking for latest version. Could not connect.")
  8000. self.log.warning("Failed checking for latest version. Could not connect.")
  8001. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8002. return
  8003. try:
  8004. data = json.load(f)
  8005. except Exception as e:
  8006. App.log.error("Could not parse information about latest version.")
  8007. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8008. App.log.debug("json.load(): %s" % str(e))
  8009. f.close()
  8010. return
  8011. f.close()
  8012. # ## Latest version?
  8013. if self.version >= data["version"]:
  8014. App.log.debug("FlatCAM is up to date!")
  8015. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8016. return
  8017. App.log.debug("Newer version available.")
  8018. self.message.emit(
  8019. _("Newer Version Available"),
  8020. '%s<br><br>><b>%s</b><br>%s' % (
  8021. _("There is a newer version of FlatCAM available for download:"),
  8022. str(data["name"]),
  8023. str(data["message"])
  8024. ),
  8025. _("info")
  8026. )
  8027. def on_plotcanvas_setup(self, container=None):
  8028. """
  8029. This is doing the setup for the plot area (canvas).
  8030. :param container: QT Widget where to install the canvas
  8031. :return: None
  8032. """
  8033. if container:
  8034. plot_container = container
  8035. else:
  8036. plot_container = self.ui.right_layout
  8037. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8038. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8039. self.is_legacy = True
  8040. self.defaults["global_graphic_engine"] = "2D"
  8041. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8042. else:
  8043. try:
  8044. self.plotcanvas = PlotCanvas(plot_container, self)
  8045. except Exception as er:
  8046. msg_txt = traceback.format_exc()
  8047. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8048. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8049. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8050. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8051. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8052. msg += msg_txt
  8053. self.inform.emit(msg)
  8054. return 'fail'
  8055. # So it can receive key presses
  8056. self.plotcanvas.native.setFocus()
  8057. if self.is_legacy is False:
  8058. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8059. # Set the mouse button for panning
  8060. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8061. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8062. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8063. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8064. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8065. # Keys over plot enabled
  8066. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8067. if self.defaults['global_cursor_type'] == 'small':
  8068. self.app_cursor = self.plotcanvas.new_cursor()
  8069. else:
  8070. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8071. if self.ui.grid_snap_btn.isChecked():
  8072. self.app_cursor.enabled = True
  8073. else:
  8074. self.app_cursor.enabled = False
  8075. if self.is_legacy is False:
  8076. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8077. else:
  8078. # will use the default Matplotlib axes
  8079. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8080. def on_zoom_fit(self):
  8081. """
  8082. Callback for zoom-fit request. This can be either from the corresponding
  8083. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8084. with axes limits from the geometry bounds of all objects.
  8085. :return: None
  8086. """
  8087. if self.is_legacy is False:
  8088. self.plotcanvas.fit_view()
  8089. else:
  8090. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8091. width = xmax - xmin
  8092. height = ymax - ymin
  8093. xmin -= 0.05 * width
  8094. xmax += 0.05 * width
  8095. ymin -= 0.05 * height
  8096. ymax += 0.05 * height
  8097. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8098. def on_zoom_in(self):
  8099. """
  8100. Callback for zoom-in request.
  8101. :return:
  8102. """
  8103. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8104. def on_zoom_out(self):
  8105. """
  8106. Callback for zoom-out request.
  8107. :return:
  8108. """
  8109. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8110. def disable_all_plots(self):
  8111. self.defaults.report_usage("disable_all_plots()")
  8112. self.disable_plots(self.collection.get_list())
  8113. self.inform.emit('[success] %s' %
  8114. _("All plots disabled."))
  8115. def disable_other_plots(self):
  8116. self.defaults.report_usage("disable_other_plots()")
  8117. self.disable_plots(self.collection.get_non_selected())
  8118. self.inform.emit('[success] %s' %
  8119. _("All non selected plots disabled."))
  8120. def enable_all_plots(self):
  8121. self.defaults.report_usage("enable_all_plots()")
  8122. self.enable_plots(self.collection.get_list())
  8123. self.inform.emit('[success] %s' %
  8124. _("All plots enabled."))
  8125. def on_enable_sel_plots(self):
  8126. log.debug("App.on_enable_sel_plot()")
  8127. object_list = self.collection.get_selected()
  8128. self.enable_plots(objects=object_list)
  8129. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8130. def on_disable_sel_plots(self):
  8131. log.debug("App.on_disable_sel_plot()")
  8132. # self.inform.emit(_("Disabling plots ..."))
  8133. object_list = self.collection.get_selected()
  8134. self.disable_plots(objects=object_list)
  8135. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8136. def enable_plots(self, objects):
  8137. """
  8138. Enable plots
  8139. :param objects: list of Objects to be enabled
  8140. :return:
  8141. """
  8142. log.debug("Enabling plots ...")
  8143. # self.inform.emit(_("Working ..."))
  8144. for obj in objects:
  8145. if obj.options['plot'] is False:
  8146. obj.options.set_change_callback(lambda x: None)
  8147. obj.options['plot'] = True
  8148. try:
  8149. # only the Gerber obj has on_plot_cb_click() method
  8150. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8151. # disable this cb while disconnected,
  8152. # in case the operation takes time the user is not allowed to change it
  8153. obj.ui.plot_cb.setDisabled(True)
  8154. except AttributeError:
  8155. pass
  8156. obj.set_form_item("plot")
  8157. try:
  8158. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8159. obj.ui.plot_cb.setDisabled(False)
  8160. except AttributeError:
  8161. pass
  8162. obj.options.set_change_callback(obj.on_options_change)
  8163. def worker_task(objs):
  8164. with self.proc_container.new(_("Enabling plots ...")):
  8165. for plot_obj in objs:
  8166. # obj.options['plot'] = True
  8167. if isinstance(plot_obj, CNCJobObject):
  8168. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8169. else:
  8170. plot_obj.plot(visible=True)
  8171. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8172. def disable_plots(self, objects):
  8173. """
  8174. Disables plots
  8175. :param objects: list of Objects to be disabled
  8176. :return:
  8177. """
  8178. # if no objects selected then do nothing
  8179. if not self.collection.get_selected():
  8180. return
  8181. log.debug("Disabling plots ...")
  8182. # self.inform.emit(_("Working ..."))
  8183. for obj in objects:
  8184. if obj.options['plot'] is True:
  8185. obj.options.set_change_callback(lambda x: None)
  8186. obj.options['plot'] = False
  8187. try:
  8188. # only the Gerber obj has on_plot_cb_click() method
  8189. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8190. obj.ui.plot_cb.setDisabled(True)
  8191. except AttributeError:
  8192. pass
  8193. obj.set_form_item("plot")
  8194. try:
  8195. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8196. obj.ui.plot_cb.setDisabled(False)
  8197. except AttributeError:
  8198. pass
  8199. obj.options.set_change_callback(obj.on_options_change)
  8200. try:
  8201. self.delete_selection_shape()
  8202. except Exception as e:
  8203. log.debug("App.disable_plots() --> %s" % str(e))
  8204. def worker_task(objs):
  8205. with self.proc_container.new(_("Disabling plots ...")):
  8206. for plot_obj in objs:
  8207. # obj.options['plot'] = True
  8208. if isinstance(plot_obj, CNCJobObject):
  8209. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8210. else:
  8211. plot_obj.plot(visible=False)
  8212. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8213. def toggle_plots(self, objects):
  8214. """
  8215. Toggle plots visibility
  8216. :param objects: list of Objects for which to be toggled the visibility
  8217. :return: None
  8218. """
  8219. # if no objects selected then do nothing
  8220. if not self.collection.get_selected():
  8221. return
  8222. log.debug("Toggling plots ...")
  8223. self.inform.emit(_("Working ..."))
  8224. for obj in objects:
  8225. if obj.options['plot'] is False:
  8226. obj.options['plot'] = True
  8227. else:
  8228. obj.options['plot'] = False
  8229. self.app_obj.plots_updated.emit()
  8230. def clear_plots(self):
  8231. """
  8232. Clear the plots
  8233. :return: None
  8234. """
  8235. objects = self.collection.get_list()
  8236. for obj in objects:
  8237. obj.clear(obj == objects[-1])
  8238. # Clear pool to free memory
  8239. self.clear_pool()
  8240. def on_set_color_action_triggered(self):
  8241. """
  8242. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8243. :return:
  8244. """
  8245. new_color = self.defaults['gerber_plot_fill']
  8246. clicked_action = self.sender()
  8247. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8248. act_name = clicked_action.text()
  8249. sel_obj_list = self.collection.get_selected()
  8250. if not sel_obj_list:
  8251. return
  8252. # a default value, I just chose this one
  8253. alpha_level = 'BF'
  8254. for sel_obj in sel_obj_list:
  8255. if sel_obj.kind == 'excellon':
  8256. alpha_level = str(hex(
  8257. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8258. elif sel_obj.kind == 'gerber':
  8259. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8260. elif sel_obj.kind == 'geometry':
  8261. alpha_level = 'FF'
  8262. else:
  8263. log.debug(
  8264. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8265. continue
  8266. sel_obj.alpha_level = alpha_level
  8267. if act_name == _('Red'):
  8268. new_color = '#FF0000' + alpha_level
  8269. if act_name == _('Blue'):
  8270. new_color = '#0000FF' + alpha_level
  8271. if act_name == _('Yellow'):
  8272. new_color = '#FFDF00' + alpha_level
  8273. if act_name == _('Green'):
  8274. new_color = '#00FF00' + alpha_level
  8275. if act_name == _('Purple'):
  8276. new_color = '#FF00FF' + alpha_level
  8277. if act_name == _('Brown'):
  8278. new_color = '#A52A2A' + alpha_level
  8279. if act_name == _('White'):
  8280. new_color = '#FFFFFF' + alpha_level
  8281. if act_name == _('Black'):
  8282. new_color = '#000000' + alpha_level
  8283. if act_name == _('Custom'):
  8284. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8285. c_dialog = QtWidgets.QColorDialog()
  8286. plot_fill_color = c_dialog.getColor(initial=new_color)
  8287. if plot_fill_color.isValid() is False:
  8288. return
  8289. new_color = str(plot_fill_color.name()) + alpha_level
  8290. if act_name == _("Default"):
  8291. for sel_obj in sel_obj_list:
  8292. if sel_obj.kind == 'excellon':
  8293. new_color = self.defaults['excellon_plot_fill']
  8294. new_line_color = self.defaults['excellon_plot_line']
  8295. elif sel_obj.kind == 'gerber':
  8296. new_color = self.defaults['gerber_plot_fill']
  8297. new_line_color = self.defaults['gerber_plot_line']
  8298. elif sel_obj.kind == 'geometry':
  8299. new_color = self.defaults['geometry_plot_line']
  8300. new_line_color = self.defaults['geometry_plot_line']
  8301. else:
  8302. log.debug(
  8303. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8304. continue
  8305. sel_obj.fill_color = new_color
  8306. sel_obj.outline_color = new_line_color
  8307. sel_obj.shapes.redraw(
  8308. update_colors=(new_color, new_line_color)
  8309. )
  8310. return
  8311. if act_name == _("Opacity"):
  8312. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8313. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8314. if ok_button:
  8315. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8316. for sel_obj in sel_obj_list:
  8317. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8318. sel_obj.shapes.redraw(
  8319. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8320. )
  8321. return
  8322. new_line_color = color_variant(new_color[:7], 0.7)
  8323. if act_name == _("White"):
  8324. new_line_color = color_variant("#dedede", 0.7)
  8325. for sel_obj in sel_obj_list:
  8326. sel_obj.fill_color = new_color
  8327. sel_obj.outline_color = new_line_color
  8328. sel_obj.shapes.redraw(
  8329. update_colors=(new_color, new_line_color)
  8330. )
  8331. def generate_cnc_job(self, objects):
  8332. """
  8333. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8334. :param objects: Selected objects in the Project Tab
  8335. :return:
  8336. """
  8337. self.defaults.report_usage("generate_cnc_job()")
  8338. # for obj in objects:
  8339. # obj.generatecncjob()
  8340. for obj in objects:
  8341. obj.on_generatecnc_button_click()
  8342. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8343. """
  8344. Saves the current project to the specified file.
  8345. :param filename: Name of the file in which to save.
  8346. :type filename: str
  8347. :param quit_action: if the project saving will be followed by an app quit; boolean
  8348. :param silent: if True will not display status messages
  8349. :param from_tcl True is run from Tcl Shell
  8350. :return: None
  8351. """
  8352. self.log.debug("save_project()")
  8353. self.save_in_progress = True
  8354. with self.proc_container.new(_("Saving FlatCAM Project")):
  8355. # Capture the latest changes
  8356. # Current object
  8357. try:
  8358. current_object = self.collection.get_active()
  8359. if current_object:
  8360. current_object.read_form()
  8361. except Exception as e:
  8362. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8363. pass
  8364. # Serialize the whole project
  8365. d = {
  8366. "objs": [obj.to_dict() for obj in self.collection.get_list()],
  8367. "options": self.options,
  8368. "version": self.version
  8369. }
  8370. if self.defaults["global_save_compressed"] is True:
  8371. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8372. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8373. # # Write
  8374. f.write(g)
  8375. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8376. else:
  8377. # Open file
  8378. try:
  8379. f = open(filename, 'w')
  8380. except IOError:
  8381. App.log.error("Failed to open file for saving: %s", filename)
  8382. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8383. return
  8384. # Write
  8385. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8386. f.close()
  8387. # verification of the saved project
  8388. # Open and parse
  8389. try:
  8390. saved_f = open(filename, 'r')
  8391. except IOError:
  8392. if silent is False:
  8393. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8394. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8395. return
  8396. try:
  8397. saved_d = json.load(saved_f, object_hook=dict2obj)
  8398. except Exception:
  8399. if silent is False:
  8400. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8401. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8402. f.close()
  8403. return
  8404. saved_f.close()
  8405. if silent is False:
  8406. if 'version' in saved_d:
  8407. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8408. else:
  8409. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8410. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8411. tb_settings = QSettings("Open Source", "FlatCAM")
  8412. lock_state = self.ui.lock_action.isChecked()
  8413. tb_settings.setValue('toolbar_lock', lock_state)
  8414. # This will write the setting to the platform specific storage.
  8415. del tb_settings
  8416. # if quit:
  8417. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8418. # t.start()
  8419. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8420. def start_delayed_quit(self, delay, filename, should_quit=None):
  8421. """
  8422. :param delay: period of checking if project file size is more than zero; in seconds
  8423. :param filename: the name of the project file to be checked periodically for size more than zero
  8424. :param should_quit: if the task finished will be followed by an app quit; boolean
  8425. :return:
  8426. """
  8427. to_quit = should_quit
  8428. self.save_timer = QtCore.QTimer()
  8429. self.save_timer.setInterval(delay)
  8430. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8431. self.save_timer.start()
  8432. def check_project_file_size(self, filename, should_quit=None):
  8433. """
  8434. :param filename: the name of the project file to be checked periodically for size more than zero
  8435. :param should_quit: will quit the app if True; boolean
  8436. :return:
  8437. """
  8438. try:
  8439. if os.stat(filename).st_size > 0:
  8440. self.save_in_progress = False
  8441. self.save_timer.stop()
  8442. if should_quit:
  8443. self.app_quit.emit()
  8444. except Exception:
  8445. traceback.print_exc()
  8446. def save_project_auto(self):
  8447. """
  8448. Called periodically to save the project.
  8449. 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
  8450. # progress.
  8451. :return:
  8452. """
  8453. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8454. self.on_file_saveproject()
  8455. def save_project_auto_update(self):
  8456. """
  8457. Update the auto save time interval value.
  8458. :return:
  8459. """
  8460. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8461. try:
  8462. if self.autosave_timer.isActive():
  8463. self.autosave_timer.stop()
  8464. except Exception:
  8465. pass
  8466. if self.defaults['global_autosave'] is True:
  8467. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8468. self.autosave_timer.start()
  8469. def on_options_app2project(self):
  8470. """
  8471. Callback for Options->Transfer Options->App=>Project. Copies options
  8472. from application defaults to project defaults.
  8473. :return: None
  8474. """
  8475. self.defaults.report_usage("on_options_app2project")
  8476. self.preferencesUiManager.defaults_read_form()
  8477. self.options.update(self.defaults)
  8478. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8479. """
  8480. Shows a message on the FlatCAM Shell
  8481. :param msg: Message to display.
  8482. :param show: Opens the shell.
  8483. :param error: Shows the message as an error.
  8484. :param warning: Shows the message as an warning.
  8485. :param success: Shows the message as an success.
  8486. :param selected: Indicate that something was selected on canvas
  8487. :return: None
  8488. """
  8489. if show:
  8490. self.ui.shell_dock.show()
  8491. try:
  8492. if error:
  8493. self.shell.append_error(msg + "\n")
  8494. elif warning:
  8495. self.shell.append_warning(msg + "\n")
  8496. elif success:
  8497. self.shell.append_success(msg + "\n")
  8498. elif selected:
  8499. self.shell.append_selected(msg + "\n")
  8500. else:
  8501. self.shell.append_output(msg + "\n")
  8502. except AttributeError:
  8503. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8504. def dec_format(self, val, dec=None):
  8505. """
  8506. Returns a formatted float value with a certain number of decimals
  8507. """
  8508. dec_nr = dec if dec is not None else self.decimals
  8509. return float('%.*f' % (dec_nr, val))
  8510. class ArgsThread(QtCore.QObject):
  8511. open_signal = pyqtSignal(list)
  8512. start = pyqtSignal()
  8513. stop = pyqtSignal()
  8514. if sys.platform == 'win32':
  8515. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8516. else:
  8517. address = ('/tmp/testipc', 'AF_UNIX')
  8518. def __init__(self):
  8519. super().__init__()
  8520. self.listener = None
  8521. self.thread_exit = False
  8522. self.start.connect(self.run)
  8523. self.stop.connect(self.close_listener)
  8524. def my_loop(self, address):
  8525. try:
  8526. self.listener = Listener(*address)
  8527. while self.thread_exit is False:
  8528. conn = self.listener.accept()
  8529. self.serve(conn)
  8530. except socket.error:
  8531. try:
  8532. conn = Client(*address)
  8533. conn.send(sys.argv)
  8534. conn.send('close')
  8535. # close the current instance only if there are args
  8536. if len(sys.argv) > 1:
  8537. try:
  8538. self.listener.close()
  8539. except Exception:
  8540. pass
  8541. sys.exit()
  8542. except ConnectionRefusedError:
  8543. if sys.platform == 'win32':
  8544. pass
  8545. else:
  8546. os.system('rm /tmp/testipc')
  8547. self.listener = Listener(*address)
  8548. while True:
  8549. conn = self.listener.accept()
  8550. self.serve(conn)
  8551. def serve(self, conn):
  8552. while self.thread_exit is False:
  8553. msg = conn.recv()
  8554. if msg == 'close':
  8555. break
  8556. self.open_signal.emit(msg)
  8557. conn.close()
  8558. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8559. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8560. @pyqtSlot()
  8561. def run(self):
  8562. self.my_loop(self.address)
  8563. @pyqtSlot()
  8564. def close_listener(self):
  8565. self.thread_exit = True
  8566. self.listener.close()
  8567. # end of file