App_Main.py 454 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146
  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 lzma
  16. import shutil
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM Objects
  45. from defaults import FlatCAMDefaults
  46. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  47. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  48. from AppObjects.ObjectCollection import *
  49. from AppObjects.FlatCAMObj import FlatCAMObj
  50. from AppObjects.AppObject import AppObject
  51. # FlatCAM Parsing files
  52. from AppParsers.ParseExcellon import Excellon
  53. from AppParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM AppGUI
  56. from AppGUI.PlotCanvas import *
  57. from AppGUI.PlotCanvasLegacy import *
  58. from AppGUI.MainGUI import *
  59. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  60. # FlatCAM Pre-processors
  61. from AppPreProcessor import load_preprocessors
  62. # FlatCAM AppEditors
  63. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from AppEditors.FlatCAMTextEditor import TextEditor
  67. from AppParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from AppProcess import *
  70. from AppWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from AppTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import AppTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. from win32comext.shell import shell, shellcon
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the AppGUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.993
  135. version_date = "2020/08/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. # Emitted when a new object has been added or deleted from/to the collection
  185. object_status_changed = QtCore.pyqtSignal(object, str, str)
  186. message = QtCore.pyqtSignal(str, str, str)
  187. # Emmited when shell command is finished(one command only)
  188. shell_command_finished = QtCore.pyqtSignal(object)
  189. # Emitted when multiprocess pool has been recreated
  190. pool_recreated = QtCore.pyqtSignal(object)
  191. # Emitted when an unhandled exception happens
  192. # in the worker task.
  193. thread_exception = QtCore.pyqtSignal(object)
  194. # used to signal that there are arguments for the app
  195. args_at_startup = QtCore.pyqtSignal(list)
  196. # a reusable signal to replot a list of objects
  197. # should be disconnected after use so it can be reused
  198. replot_signal = pyqtSignal(list)
  199. # signal emitted when jumping
  200. jump_signal = pyqtSignal(tuple)
  201. # signal emitted when jumping
  202. locate_signal = pyqtSignal(tuple, str)
  203. # close app signal
  204. close_app_signal = pyqtSignal()
  205. # will perform the cleanup operation after a Graceful Exit
  206. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  207. # graphic residues behind
  208. cleanup = pyqtSignal()
  209. def __init__(self, user_defaults=True):
  210. """
  211. Starts the application.
  212. :return: app
  213. :rtype: App
  214. """
  215. super().__init__()
  216. App.log.info("FlatCAM Starting...")
  217. self.main_thread = QtWidgets.QApplication.instance().thread()
  218. # ############################################################################################################
  219. # ################# Setup the listening thread for another instance launching with args ######################
  220. # ############################################################################################################
  221. if sys.platform == 'win32' or sys.platform == 'linux':
  222. # make sure the thread is stored by using a self. otherwise it's garbage collected
  223. self.th = QtCore.QThread()
  224. self.th.start(priority=QtCore.QThread.LowestPriority)
  225. self.new_launch = ArgsThread()
  226. self.new_launch.open_signal[list].connect(self.on_startup_args)
  227. self.new_launch.moveToThread(self.th)
  228. self.new_launch.start.emit()
  229. # ############################################################################################################
  230. # # ######################################## OS-specific #####################################################
  231. # ############################################################################################################
  232. portable = False
  233. # Folder for user settings.
  234. if sys.platform == 'win32':
  235. if platform.architecture()[0] == '32bit':
  236. App.log.debug("Win32!")
  237. else:
  238. App.log.debug("Win64!")
  239. # #######################################################################################################
  240. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  241. # #######################################################################################################
  242. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  243. try:
  244. with open(config_file, 'r'):
  245. pass
  246. except FileNotFoundError:
  247. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  248. try:
  249. with open(config_file, 'r') as f:
  250. try:
  251. for line in f:
  252. param = str(line).replace('\n', '').rpartition('=')
  253. if param[0] == 'portable':
  254. try:
  255. portable = eval(param[2])
  256. except NameError:
  257. portable = False
  258. if param[0] == 'headless':
  259. if param[2].lower() == 'true':
  260. self.cmd_line_headless = 1
  261. else:
  262. self.cmd_line_headless = None
  263. except Exception as e:
  264. log.debug('App.__init__() -->%s' % str(e))
  265. return
  266. except FileNotFoundError as e:
  267. log.debug(str(e))
  268. pass
  269. if portable is False:
  270. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  271. else:
  272. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  273. self.os = 'windows'
  274. else: # Linux/Unix/MacOS
  275. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  276. self.os = 'unix'
  277. # ############################################################################################################
  278. # ################################# Setup folders and files ##################################################
  279. # ############################################################################################################
  280. if not os.path.exists(self.data_path):
  281. os.makedirs(self.data_path)
  282. App.log.debug('Created data folder: ' + self.data_path)
  283. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  284. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  285. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  286. if not os.path.exists(self.preprocessorpaths):
  287. os.makedirs(self.preprocessorpaths)
  288. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  289. # create geo_tools_db.FlatDB file if there is none
  290. try:
  291. f = open(self.data_path + '/geo_tools_db.FlatDB')
  292. f.close()
  293. except IOError:
  294. App.log.debug('Creating empty geo_tool_db.FlatDB')
  295. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  296. json.dump({}, f)
  297. f.close()
  298. # create current_defaults.FlatConfig file if there is none
  299. try:
  300. f = open(self.data_path + '/current_defaults.FlatConfig')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty current_defaults.FlatConfig')
  304. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # Write factory_defaults.FlatConfig file to disk
  308. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  309. # create a recent files json file if there is none
  310. try:
  311. f = open(self.data_path + '/recent.json')
  312. f.close()
  313. except IOError:
  314. App.log.debug('Creating empty recent.json')
  315. f = open(self.data_path + '/recent.json', 'w')
  316. json.dump([], f)
  317. f.close()
  318. # create a recent projects json file if there is none
  319. try:
  320. fp = open(self.data_path + '/recent_projects.json')
  321. fp.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent_projects.json')
  324. fp = open(self.data_path + '/recent_projects.json', 'w')
  325. json.dump([], fp)
  326. fp.close()
  327. # Application directory. CHDIR to it. Otherwise, trying to load
  328. # GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. App.log.debug("Application path is " + self.app_home)
  332. App.log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. self.ui = MainGUI(self)
  397. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  398. if theme_settings.contains("theme"):
  399. theme = theme_settings.value('theme', type=str)
  400. else:
  401. theme = 'white'
  402. if self.defaults["global_cursor_color_enabled"]:
  403. self.cursor_color_3D = self.defaults["global_cursor_color"]
  404. else:
  405. if theme == 'white':
  406. self.cursor_color_3D = 'black'
  407. else:
  408. self.cursor_color_3D = 'gray'
  409. # update the defaults dict with the setting in QSetting
  410. self.defaults['global_theme'] = theme
  411. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  412. self.ui.final_save.connect(self.final_save)
  413. # set FlatCAM units in the Status bar
  414. self.set_screen_units(self.defaults['units'])
  415. # ###########################################################################################################
  416. # ########################################### AUTOSAVE SETUP ################################################
  417. # ###########################################################################################################
  418. self.block_autosave = False
  419. self.autosave_timer = QtCore.QTimer(self)
  420. self.save_project_auto_update()
  421. self.autosave_timer.timeout.connect(self.save_project_auto)
  422. # ###########################################################################################################
  423. # #################################### LOAD PREPROCESSORS ###################################################
  424. # ###########################################################################################################
  425. # ----------------------------------------- WARNING --------------------------------------------------------
  426. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  427. # That's because the number of preprocessors can vary and here the comboboxes are populated
  428. # -----------------------------------------------------------------------------------------------------------
  429. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  430. # the preprocessor file
  431. self.preprocessors = load_preprocessors(self)
  432. # make sure that always the 'default' preprocessor is the first item in the dictionary
  433. if 'default' in self.preprocessors.keys():
  434. new_ppp_dict = {}
  435. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  436. default_pp = self.preprocessors.pop('default')
  437. new_ppp_dict['default'] = default_pp
  438. # then add the rest of the keys
  439. for name, val_class in self.preprocessors.items():
  440. new_ppp_dict[name] = val_class
  441. # and now put back the ordered dict with 'default' key first
  442. self.preprocessors = new_ppp_dict
  443. for name in list(self.preprocessors.keys()):
  444. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  445. if name.partition('_')[0] == 'Paste':
  446. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  447. continue
  448. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  449. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  450. if name == 'hpgl':
  451. continue
  452. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  453. # ###########################################################################################################
  454. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  455. # ###########################################################################################################
  456. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  457. inform=self.inform)
  458. self.preferencesUiManager.defaults_write_form()
  459. # When the self.defaults dictionary changes will update the Preferences GUI forms
  460. self.defaults.set_change_callback(self.on_defaults_dict_change)
  461. # ###########################################################################################################
  462. # ##################################### FIRST RUN SECTION ###################################################
  463. # ################################ It's done only once after install #####################################
  464. # ###########################################################################################################
  465. if self.defaults["first_run"] is True:
  466. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  467. initial_lay = 'minimal'
  468. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  469. # Set the combobox in Preferences to the current layout
  470. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  471. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  472. # after the first run, this object should be False
  473. self.defaults["first_run"] = False
  474. self.preferencesUiManager.save_defaults(silent=True)
  475. # ###########################################################################################################
  476. # ############################################ Data #########################################################
  477. # ###########################################################################################################
  478. self.recent = []
  479. self.recent_projects = []
  480. self.clipboard = QtWidgets.QApplication.clipboard()
  481. self.project_filename = None
  482. self.toggle_units_ignore = False
  483. # ###########################################################################################################
  484. # ########################################## LOAD LANGUAGES ################################################
  485. # ###########################################################################################################
  486. self.languages = fcTranslate.load_languages()
  487. for name in sorted(self.languages.values()):
  488. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  489. # ###########################################################################################################
  490. # ####################################### APPLY APP LANGUAGE ################################################
  491. # ###########################################################################################################
  492. ret_val = fcTranslate.apply_language('strings')
  493. if ret_val == "no language":
  494. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  495. log.debug("Could not find the Language files. The App strings are missing.")
  496. else:
  497. # make the current language the current selection on the language combobox
  498. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  499. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  500. # ###########################################################################################################
  501. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  502. # ###########################################################################################################
  503. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  504. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  505. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  506. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  507. self.defaults.propagate_defaults()
  508. # ###########################################################################################################
  509. # ######################################## UPDATE THE OPTIONS ###############################################
  510. # ###########################################################################################################
  511. self.options = LoudDict()
  512. # -----------------------------------------------------------------------------------------------------------
  513. # Update the self.options from the self.defaults
  514. # The self.defaults holds the application defaults while the self.options holds the object defaults
  515. # -----------------------------------------------------------------------------------------------------------
  516. # Copy app defaults to project options
  517. for def_key, def_val in self.defaults.items():
  518. self.options[def_key] = deepcopy(def_val)
  519. self.preferencesUiManager.show_preferences_gui()
  520. # ### End of Data ####
  521. # ###########################################################################################################
  522. # #################################### SETUP OBJECT COLLECTION ##############################################
  523. # ###########################################################################################################
  524. self.collection = ObjectCollection(app=self)
  525. self.ui.project_tab_layout.addWidget(self.collection.view)
  526. self.app_obj = AppObject(app=self)
  527. # ### Adjust tabs width ## ##
  528. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  529. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  530. self.collection.view.setMinimumWidth(290)
  531. self.log.debug("Finished creating Object Collection.")
  532. # ###########################################################################################################
  533. # ######################################## SETUP Plot Area ##################################################
  534. # ###########################################################################################################
  535. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  536. if self.defaults["global_graphic_engine"] == '3D':
  537. self.is_legacy = False
  538. else:
  539. self.is_legacy = True
  540. # Event signals disconnect id holders
  541. self.mp = None
  542. self.mm = None
  543. self.mr = None
  544. self.mdc = None
  545. self.mp_zc = None
  546. self.kp = None
  547. # Matplotlib axis
  548. self.axes = None
  549. if show_splash:
  550. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  551. "Canvas initialization started."),
  552. alignment=Qt.AlignBottom | Qt.AlignLeft,
  553. color=QtGui.QColor("gray"))
  554. start_plot_time = time.time() # debug
  555. self.plotcanvas = None
  556. self.app_cursor = None
  557. self.hover_shapes = None
  558. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  559. # setup the PlotCanvas
  560. self.on_plotcanvas_setup()
  561. end_plot_time = time.time()
  562. self.used_time = end_plot_time - start_plot_time
  563. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  564. if show_splash:
  565. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  566. "Canvas initialization started.\n"
  567. "Canvas initialization finished in"), '%.2f' % self.used_time),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. self.ui.splitter.setStretchFactor(1, 2)
  571. # ###########################################################################################################
  572. # ############################################### SYS TRAY ##################################################
  573. # ###########################################################################################################
  574. if self.defaults["global_systray_icon"]:
  575. self.parent_w = QtWidgets.QWidget()
  576. if self.cmd_line_headless == 1:
  577. self.trayIcon = FlatCAMSystemTray(app=self,
  578. icon=QtGui.QIcon(self.resource_location +
  579. '/flatcam_icon32_green.png'),
  580. headless=True,
  581. parent=self.parent_w)
  582. else:
  583. self.trayIcon = FlatCAMSystemTray(app=self,
  584. icon=QtGui.QIcon(self.resource_location +
  585. '/flatcam_icon32_green.png'),
  586. parent=self.parent_w)
  587. # ###########################################################################################################
  588. # ############################################### Worker SETUP ##############################################
  589. # ###########################################################################################################
  590. if self.defaults["global_worker_number"]:
  591. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  592. else:
  593. self.workers = WorkerStack(workers_number=2)
  594. self.worker_task.connect(self.workers.add_task)
  595. self.log.debug("Finished creating Workers crew.")
  596. # ###########################################################################################################
  597. # ############################################# Activity Monitor ###########################################
  598. # ###########################################################################################################
  599. self.activity_view = FlatCAMActivityView(app=self)
  600. self.ui.infobar.addWidget(self.activity_view)
  601. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  602. # ###########################################################################################################
  603. # ############################################# Signal handling #############################################
  604. # ###########################################################################################################
  605. # ########################################## Custom signals ################################################
  606. # signal for displaying messages in status bar
  607. self.inform.connect(self.info)
  608. # signal to be called when the app is quiting
  609. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  610. self.message.connect(lambda: message_dialog(parent=self.ui))
  611. # self.progress.connect(self.set_progress_bar)
  612. # signals emitted when file state change
  613. self.file_opened.connect(self.register_recent)
  614. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  615. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  616. # ########################################## Standard signals ###############################################
  617. # ### Menu
  618. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  619. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  620. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  621. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  622. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  623. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  624. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  625. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  626. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  627. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  628. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  629. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  630. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  631. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  632. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  633. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  634. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  635. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  636. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  637. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  638. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  639. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  640. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  641. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  642. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  643. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  644. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  645. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  646. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  647. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  648. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  649. self.ui.menufile_exit.triggered.connect(self.final_save)
  650. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  651. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  652. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  653. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  654. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  655. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  656. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  657. self.ui.menueditdelete.triggered.connect(self.on_delete)
  658. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  659. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  660. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  661. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  662. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  663. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  664. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  665. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  666. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  667. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  668. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  669. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  670. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  671. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  672. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  673. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  674. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  675. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  676. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  677. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  678. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  679. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  680. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  681. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  682. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  683. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  684. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  685. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  686. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  687. self.ui.menuview_replot.triggered.connect(self.plot_all)
  688. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  689. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  690. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  691. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  692. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  693. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  694. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  695. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  696. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  697. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  698. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  699. self.ui.menuhelp_about.triggered.connect(self.on_about)
  700. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  701. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  702. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  703. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  704. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  705. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  706. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  707. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  708. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  709. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  710. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  711. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  712. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  713. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  714. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  715. # ToolBar signals
  716. self.connect_toolbar_signals()
  717. # Notebook and Plot Tab Area signals
  718. # make the right click on the notebook tab and plot tab area tab raise a menu
  719. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. self.on_tab_setup_context_menu()
  722. # activate initial state
  723. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  724. # Context Menu
  725. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  726. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  727. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  728. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  729. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  730. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  731. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  732. self.ui.clearplot.triggered.connect(self.clear_plots)
  733. self.ui.replot.triggered.connect(self.plot_all)
  734. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  735. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  736. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  737. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  738. self.ui.popmenu_move.triggered.connect(self.obj_move)
  739. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  740. # Project Context Menu -> Color Setting
  741. for act in self.ui.menuprojectcolor.actions():
  742. act.triggered.connect(self.on_set_color_action_triggered)
  743. # ###########################################################################################################
  744. # #################################### GUI PREFERENCES SIGNALS ##############################################
  745. # ###########################################################################################################
  746. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  747. lambda: self.on_toggle_units(no_pref=False))
  748. # ##################################### Workspace Setting Signals ###########################################
  749. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  750. self.on_workspace_modified)
  751. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  752. self.on_workspace_modified
  753. )
  754. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  755. # ###########################################################################################################
  756. # ######################################## GUI SETTINGS SIGNALS #############################################
  757. # ###########################################################################################################
  758. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  759. # ######################################## Tools related signals ############################################
  760. # Film Tool
  761. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  762. self.on_film_color_entry)
  763. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  764. self.on_film_color_button)
  765. # QRCode Tool
  766. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  767. self.on_qrcode_fill_color_entry)
  768. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  769. self.on_qrcode_fill_color_button)
  770. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  771. self.on_qrcode_back_color_entry)
  772. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  773. self.on_qrcode_back_color_button)
  774. # portability changed signal
  775. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  776. # Object list
  777. self.object_status_changed.connect(self.collection.on_collection_updated)
  778. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  779. # Export Excellon parameters.
  780. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  781. self.on_update_exc_export
  782. )
  783. # call it once to make sure it is updated at startup
  784. self.on_update_exc_export(state=self.defaults["excellon_update"])
  785. # when there are arguments at application startup this get launched
  786. self.args_at_startup[list].connect(self.on_startup_args)
  787. # ###########################################################################################################
  788. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  789. # ###########################################################################################################
  790. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  791. lambda: self.restore_extensions(ext_type='excellon'))
  792. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='gcode'))
  794. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  795. lambda: self.restore_extensions(ext_type='gerber'))
  796. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  797. lambda: self.delete_all_extensions(ext_type='excellon'))
  798. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='gcode'))
  800. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  801. lambda: self.delete_all_extensions(ext_type='gerber'))
  802. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  803. lambda: self.add_extension(ext_type='excellon'))
  804. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='gcode'))
  806. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='gerber'))
  808. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  809. lambda: self.del_extension(ext_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  813. lambda: self.del_extension(ext_type='gerber'))
  814. # connect the 'Apply' buttons from the Preferences/File Associations
  815. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  816. lambda: self.on_register_files(obj_type='excellon'))
  817. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='gcode'))
  819. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  820. lambda: self.on_register_files(obj_type='gerber'))
  821. # ###########################################################################################################
  822. # ########################################### KEYWORDS SIGNALS ##############################################
  823. # ###########################################################################################################
  824. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  825. lambda: self.restore_extensions(ext_type='keyword'))
  826. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  827. lambda: self.delete_all_extensions(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  829. lambda: self.add_extension(ext_type='keyword'))
  830. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='keyword'))
  832. # connect the abort_all_tasks related slots to the related signals
  833. self.proc_container.idle_flag.connect(self.app_is_idle)
  834. # signal emitted when a tab is closed in the Plot Area
  835. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  836. # signal to close the application
  837. self.close_app_signal.connect(self.kill_app)
  838. # ################################# FINISHED CONNECTING SIGNALS #############################################
  839. # ###########################################################################################################
  840. # ###########################################################################################################
  841. # ###########################################################################################################
  842. self.log.debug("Finished connecting Signals.")
  843. # ###########################################################################################################
  844. # ########################################## Other setups ###################################################
  845. # ###########################################################################################################
  846. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  847. # depending on from where those tools are called different actions can be done
  848. self.call_source = 'app'
  849. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  850. self.tool_tab_locked = False
  851. # decide if to show or hide the Notebook side of the screen at startup
  852. if self.defaults["global_project_at_startup"] is True:
  853. self.ui.splitter.setSizes([1, 1])
  854. else:
  855. self.ui.splitter.setSizes([0, 1])
  856. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  857. self.setup_component_editor()
  858. # ###########################################################################################################
  859. # ####################################### Auto-complete KEYWORDS ############################################
  860. # ###########################################################################################################
  861. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  862. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  863. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  864. 'export_exc',
  865. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  866. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  867. 'interiors', 'isolate', 'join_excellon',
  868. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  869. 'mirror', 'ncc',
  870. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  871. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  872. 'options', 'origin',
  873. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  874. 'save', 'save_project',
  875. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  876. 'skew', 'subtract_poly', 'subtract_rectangle',
  877. 'version', 'write_gcode'
  878. ]
  879. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  880. 'Paste_1',
  881. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  882. 'Toolchange_manual', 'True', 'Users',
  883. 'all', 'auto', 'axis',
  884. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  885. 'contour', 'default',
  886. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  887. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  888. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  889. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  890. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  891. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  892. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  893. 'spacing_columns',
  894. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  895. 'toolchange_xy', 'toolchangez', 'travelz',
  896. 'tooldia', 'use_threads', 'value',
  897. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  898. ]
  899. self.tcl_keywords = [
  900. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  901. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  902. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  903. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  904. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  905. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  906. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  907. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  908. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  909. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  910. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  911. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  912. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  913. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  914. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  915. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  916. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  917. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  918. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  919. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  920. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  921. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  922. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  923. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  924. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  925. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  926. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  927. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  928. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  929. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  930. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  931. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  932. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  933. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  934. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  935. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  936. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  937. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  938. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  939. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  940. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  941. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  942. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  943. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  944. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  945. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  946. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  947. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  948. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  949. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  950. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  951. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  952. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  953. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  954. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  955. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  956. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  957. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  958. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  959. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  960. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  961. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  962. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  963. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  964. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  965. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  966. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  967. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  968. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  969. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  970. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  971. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  972. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  973. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  974. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  975. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  976. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  977. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  978. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  979. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  980. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  981. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  982. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  983. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  984. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  985. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  986. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  987. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  988. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  989. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  990. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  991. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  992. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  993. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  994. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  995. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  996. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  997. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  998. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  999. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1000. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1001. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1002. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1003. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1004. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1005. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1006. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1007. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1008. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1009. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1010. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1011. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1012. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1013. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1014. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1015. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1016. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1017. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1018. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1019. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1020. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1021. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1022. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1023. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1024. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1025. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1026. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1027. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1028. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1029. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1030. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1031. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1032. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1033. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1034. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1035. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1036. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1037. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1038. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1039. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1040. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1041. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1042. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1043. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1044. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1045. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1046. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1047. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1048. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1049. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1050. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1051. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1052. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1053. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1054. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1055. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1056. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1057. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1058. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1059. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1060. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1061. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1062. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1063. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1064. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1065. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1066. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1067. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1068. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1069. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1070. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1071. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1072. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1073. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1074. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1075. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1076. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1077. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1078. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1079. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1080. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1081. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1082. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1083. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1084. ]
  1085. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1086. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1087. # ###########################################################################################################
  1088. # ############################################## Shell SETUP ################################################
  1089. # ###########################################################################################################
  1090. self.shell = FCShell(app=self, version=self.version)
  1091. self.ui.shell_dock.setWidget(self.shell)
  1092. self.log.debug("TCL Shell has been initialized.")
  1093. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1094. if self.defaults["global_shell_at_startup"]:
  1095. self.ui.shell_dock.show()
  1096. else:
  1097. self.ui.shell_dock.hide()
  1098. # ###########################################################################################################
  1099. # ########################################## Tools and Plugins ##############################################
  1100. # ###########################################################################################################
  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.optimal_tool = None
  1114. self.paint_tool = None
  1115. self.transform_tool = None
  1116. self.properties_tool = None
  1117. self.pdf_tool = None
  1118. self.image_tool = None
  1119. self.pcb_wizard_tool = None
  1120. self.cal_exc_tool = None
  1121. self.qrcode_tool = None
  1122. self.copper_thieving_tool = None
  1123. self.fiducial_tool = None
  1124. self.edrills_tool = None
  1125. self.align_objects_tool = None
  1126. self.punch_tool = None
  1127. self.invert_tool = None
  1128. self.corners_tool = None
  1129. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1130. try:
  1131. self.install_tools()
  1132. except AttributeError as e:
  1133. log.debug("App.__init__() install tools() --> %s" % str(e))
  1134. # ###########################################################################################################
  1135. # ############################################ SETUP RECENT ITEMS ###########################################
  1136. # ###########################################################################################################
  1137. self.setup_recent_items()
  1138. # ###########################################################################################################
  1139. # ######################################### BookMarks Manager ###############################################
  1140. # ###########################################################################################################
  1141. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1142. self.install_bookmarks()
  1143. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1144. # ###########################################################################################################
  1145. # ########################################### Tools Database ################################################
  1146. # ###########################################################################################################
  1147. self.tools_db_tab = None
  1148. # ### System Font Parsing ###
  1149. # self.f_parse = ParseFont(self)
  1150. # self.parse_system_fonts()
  1151. # ###########################################################################################################
  1152. # ######################################### Check for updates ###############################################
  1153. # ###########################################################################################################
  1154. # Separate thread (Not worker)
  1155. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1156. if (self.beta is False or self.beta is None) and \
  1157. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1158. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1159. # self.thr2 = QtCore.QThread()
  1160. self.worker_task.emit({'fcn': self.version_check,
  1161. 'params': []})
  1162. # self.thr2.start(QtCore.QThread.LowPriority)
  1163. # ###########################################################################################################
  1164. # ##################################### Register files with FlatCAM; #######################################
  1165. # ################################### It works only for Windows for now ####################################
  1166. # ###########################################################################################################
  1167. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1168. self.on_register_files()
  1169. # ###########################################################################################################
  1170. # ######################################## Variables for global usage #######################################
  1171. # ###########################################################################################################
  1172. # hold the App units
  1173. self.units = 'MM'
  1174. # coordinates for relative position display
  1175. self.rel_point1 = (0, 0)
  1176. self.rel_point2 = (0, 0)
  1177. # variable to store coordinates
  1178. self.pos = (0, 0)
  1179. self.pos_canvas = (0, 0)
  1180. self.pos_jump = (0, 0)
  1181. # variable to store mouse coordinates
  1182. self.mouse = [0, 0]
  1183. # variable to store the delta positions on cavnas
  1184. self.dx = 0
  1185. self.dy = 0
  1186. # decide if we have a double click or single click
  1187. self.doubleclick = False
  1188. # store here the is_dragging value
  1189. self.event_is_dragging = False
  1190. # variable to store if a command is active (then the var is not None) and which one it is
  1191. self.command_active = None
  1192. # variable to store the status of moving selection action
  1193. # None value means that it's not an selection action
  1194. # True value = a selection from left to right
  1195. # False value = a selection from right to left
  1196. self.selection_type = None
  1197. # List to store the objects that are currently loaded in FlatCAM
  1198. # This list is updated on each object creation or object delete
  1199. self.all_objects_list = []
  1200. self.objects_under_the_click_list = []
  1201. # List to store the objects that are selected
  1202. self.sel_objects_list = []
  1203. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1204. self.key_modifiers = None
  1205. # Variable to hold the status of the axis
  1206. self.toggle_axis = True
  1207. # Variable to hold the status of the grid lines
  1208. self.toggle_grid_lines = True
  1209. # Variable to store the status of the code editor
  1210. self.toggle_codeeditor = False
  1211. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1212. self.click_noproject = False
  1213. self.cursor = None
  1214. # Variable to store the GCODE that was edited
  1215. self.gcode_edited = ""
  1216. self.text_editor_tab = None
  1217. # reference for the self.ui.code_editor
  1218. self.reference_code_editor = None
  1219. self.script_code = ''
  1220. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1221. self.tools_db_changed_flag = False
  1222. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1223. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1224. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1225. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1226. 'tsm']
  1227. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1228. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1229. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1230. 'sbp', 'tap', 'xpi']
  1231. self.svg_list = ['svg']
  1232. self.dxf_list = ['dxf']
  1233. self.pdf_list = ['pdf']
  1234. self.prj_list = ['flatprj']
  1235. self.conf_list = ['flatconfig']
  1236. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1237. # flag for polygons not cleared
  1238. self.poly_not_cleared = False
  1239. # VisPy visuals
  1240. self.isHovering = False
  1241. self.notHovering = True
  1242. # Window geometry
  1243. self.x_pos = None
  1244. self.y_pos = None
  1245. self.width = None
  1246. self.height = None
  1247. # when True, the app has to return from any thread
  1248. self.abort_flag = False
  1249. # set the value used in the Windows Title
  1250. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1251. # this holds a widget that is installed in the Plot Area when View Source option is used
  1252. self.source_editor_tab = None
  1253. self.pagesize = {}
  1254. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1255. # VisPy visuals
  1256. if self.is_legacy is False:
  1257. try:
  1258. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1259. except AttributeError:
  1260. self.tool_shapes = None
  1261. else:
  1262. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1263. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1264. # used in the delayed shutdown self.start_delayed_quit() method
  1265. self.save_timer = None
  1266. # ###########################################################################################################
  1267. # ################################## ADDING FlatCAM EDITORS section #########################################
  1268. # ###########################################################################################################
  1269. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1270. # at the first launch of the App , the editors will not be functional.
  1271. try:
  1272. self.geo_editor = FlatCAMGeoEditor(self)
  1273. except AttributeError:
  1274. pass
  1275. try:
  1276. self.exc_editor = FlatCAMExcEditor(self)
  1277. except AttributeError:
  1278. pass
  1279. try:
  1280. self.grb_editor = FlatCAMGrbEditor(self)
  1281. except AttributeError:
  1282. pass
  1283. self.log.debug("Finished adding FlatCAM Editor's.")
  1284. self.set_ui_title(name=_("New Project - Not saved"))
  1285. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1286. current_platform = platform.architecture()[0]
  1287. if current_platform != '64bit':
  1288. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1289. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1290. # ###########################################################################################################
  1291. # ########################################### EXCLUSION AREAS ###############################################
  1292. # ###########################################################################################################
  1293. self.exc_areas = ExclusionAreas(app=self)
  1294. # ###########################################################################################################
  1295. # ##################################### Finished the CONSTRUCTOR ############################################
  1296. # ###########################################################################################################
  1297. App.log.debug("END of constructor. Releasing control.")
  1298. # ###########################################################################################################
  1299. # ########################################## SHOW GUI #######################################################
  1300. # ###########################################################################################################
  1301. # if the app is not started as headless, show it
  1302. if self.cmd_line_headless != 1:
  1303. if show_splash:
  1304. # finish the splash
  1305. self.splash.finish(self.ui)
  1306. mgui_settings = QSettings("Open Source", "FlatCAM")
  1307. if mgui_settings.contains("maximized_gui"):
  1308. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1309. if maximized_ui is True:
  1310. self.ui.showMaximized()
  1311. else:
  1312. self.ui.show()
  1313. else:
  1314. self.ui.show()
  1315. if self.defaults["global_systray_icon"]:
  1316. self.trayIcon.show()
  1317. else:
  1318. log.warning("******************* RUNNING HEADLESS *******************")
  1319. # ###########################################################################################################
  1320. # ######################################## START-UP ARGUMENTS ###############################################
  1321. # ###########################################################################################################
  1322. # test if the program was started with a script as parameter
  1323. if self.cmd_line_shellvar:
  1324. try:
  1325. cnt = 0
  1326. command_tcl = 0
  1327. for i in self.cmd_line_shellvar.split(','):
  1328. if i is not None:
  1329. # noinspection PyBroadException
  1330. try:
  1331. command_tcl = eval(i)
  1332. except Exception:
  1333. command_tcl = i
  1334. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1335. cnt += 1
  1336. # if there are Windows paths then replace the path separator with a Unix like one
  1337. if sys.platform == 'win32':
  1338. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1339. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1340. except Exception as ext:
  1341. print("ERROR: ", ext)
  1342. sys.exit(2)
  1343. if self.cmd_line_shellfile:
  1344. if self.cmd_line_headless != 1:
  1345. if self.ui.shell_dock.isHidden():
  1346. self.ui.shell_dock.show()
  1347. try:
  1348. with open(self.cmd_line_shellfile, "r") as myfile:
  1349. # if show_splash:
  1350. # self.splash.showMessage('%s: %ssec\n%s' % (
  1351. # _("Canvas initialization started.\n"
  1352. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1353. # _("Executing Tcl Script ...")),
  1354. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1355. # color=QtGui.QColor("gray"))
  1356. cmd_line_shellfile_text = myfile.read()
  1357. if self.cmd_line_headless != 1:
  1358. self.shell.exec_command(cmd_line_shellfile_text)
  1359. else:
  1360. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1361. except Exception as ext:
  1362. print("ERROR: ", ext)
  1363. sys.exit(2)
  1364. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1365. # the path/file_name must be enclosed in quotes if it contain spaces
  1366. if App.args:
  1367. self.args_at_startup.emit(App.args)
  1368. if self.defaults.old_defaults_found is True:
  1369. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1370. "Please reboot the application to update."))
  1371. self.defaults.old_defaults_found = False
  1372. # ######################################### INIT FINISHED #######################################################
  1373. # #################################################################################################################
  1374. # #################################################################################################################
  1375. # #################################################################################################################
  1376. # #################################################################################################################
  1377. # #################################################################################################################
  1378. @staticmethod
  1379. def copy_and_overwrite(from_path, to_path):
  1380. """
  1381. From here:
  1382. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1383. :param from_path: source path
  1384. :param to_path: destination path
  1385. :return: None
  1386. """
  1387. if os.path.exists(to_path):
  1388. shutil.rmtree(to_path)
  1389. try:
  1390. shutil.copytree(from_path, to_path)
  1391. except FileNotFoundError:
  1392. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1393. shutil.copytree(from_new_path, to_path)
  1394. def on_startup_args(self, args, silent=False):
  1395. """
  1396. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1397. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1398. :param args: a list containing the application args at startup
  1399. :return: None
  1400. """
  1401. if args is not None:
  1402. args_to_process = args
  1403. else:
  1404. args_to_process = App.args
  1405. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1406. for argument in args_to_process:
  1407. if '.FlatPrj'.lower() in argument.lower():
  1408. try:
  1409. project_name = str(argument)
  1410. if project_name == "":
  1411. if silent is False:
  1412. self.inform.emit(_("Cancelled."))
  1413. else:
  1414. # self.open_project(project_name)
  1415. run_from_arg = True
  1416. # self.worker_task.emit({'fcn': self.open_project,
  1417. # 'params': [project_name, run_from_arg]})
  1418. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1419. except Exception as e:
  1420. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1421. elif '.FlatConfig'.lower() in argument.lower():
  1422. try:
  1423. file_name = str(argument)
  1424. if file_name == "":
  1425. if silent is False:
  1426. self.inform.emit(_("Open Config file failed."))
  1427. else:
  1428. run_from_arg = True
  1429. # self.worker_task.emit({'fcn': self.open_config_file,
  1430. # 'params': [file_name, run_from_arg]})
  1431. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1432. except Exception as e:
  1433. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1434. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1435. try:
  1436. file_name = str(argument)
  1437. if file_name == "":
  1438. if silent is False:
  1439. self.inform.emit(_("Open Script file failed."))
  1440. else:
  1441. if silent is False:
  1442. self.on_fileopenscript(name=file_name)
  1443. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1444. self.on_filerunscript(name=file_name)
  1445. except Exception as e:
  1446. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1447. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1448. log.debug("App.on_startup_args() --> Quit event.")
  1449. sys.exit()
  1450. elif 'save'.lower() in argument.lower():
  1451. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1452. self.preferencesUiManager.save_defaults()
  1453. else:
  1454. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1455. proc_arg = argument.lower()
  1456. for ext in exc_list:
  1457. proc_ext = ext.replace(' ', '')
  1458. proc_ext = '.%s' % proc_ext
  1459. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1460. file_name = str(argument)
  1461. if file_name == "":
  1462. if silent is False:
  1463. self.inform.emit(_("Open Excellon file failed."))
  1464. else:
  1465. self.on_fileopenexcellon(name=file_name, signal=None)
  1466. return
  1467. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1468. for ext in gco_list:
  1469. proc_ext = ext.replace(' ', '')
  1470. proc_ext = '.%s' % proc_ext
  1471. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1472. file_name = str(argument)
  1473. if file_name == "":
  1474. if silent is False:
  1475. self.inform.emit(_("Open GCode file failed."))
  1476. else:
  1477. self.on_fileopengcode(name=file_name, signal=None)
  1478. return
  1479. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1480. for ext in grb_list:
  1481. proc_ext = ext.replace(' ', '')
  1482. proc_ext = '.%s' % proc_ext
  1483. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1484. file_name = str(argument)
  1485. if file_name == "":
  1486. if silent is False:
  1487. self.inform.emit(_("Open Gerber file failed."))
  1488. else:
  1489. self.on_fileopengerber(name=file_name, signal=None)
  1490. return
  1491. # if it reached here without already returning then the app was registered with a file that it does not
  1492. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1493. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1494. # for arg in args_to_process:
  1495. # if 'FlatCAM.exe' in arg:
  1496. # continue
  1497. # else:
  1498. # sys.exit(2)
  1499. def set_ui_title(self, name):
  1500. """
  1501. Sets the title of the main window.
  1502. :param name: String that store the project path and project name
  1503. :return: None
  1504. """
  1505. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1506. (self.version,
  1507. ('BETA' if self.beta else ''),
  1508. platform.architecture()[0],
  1509. self.engine,
  1510. name)
  1511. )
  1512. def on_app_restart(self):
  1513. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1514. # be left in the SySTray
  1515. try:
  1516. self.trayIcon.hide()
  1517. except Exception:
  1518. pass
  1519. fcTranslate.restart_program(app=self)
  1520. def clear_pool(self):
  1521. """
  1522. Clear the multiprocessing pool and calls garbage collector.
  1523. :return: None
  1524. """
  1525. self.pool.close()
  1526. self.pool = Pool()
  1527. self.pool_recreated.emit(self.pool)
  1528. gc.collect()
  1529. def install_tools(self):
  1530. """
  1531. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1532. Instantiation of the Tools classes.
  1533. The order that the tools are installed is important as they can depend on each other install position.
  1534. :return: None
  1535. """
  1536. self.distance_tool = Distance(self)
  1537. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1538. before=self.ui.menueditorigin,
  1539. separator=False)
  1540. self.distance_min_tool = DistanceMin(self)
  1541. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1542. pos=self.ui.menuedit,
  1543. before=self.ui.menueditorigin,
  1544. separator=True)
  1545. self.dblsidedtool = DblSidedTool(self)
  1546. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1547. self.cal_exc_tool = ToolCalibration(self)
  1548. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1549. before=self.dblsidedtool.menuAction,
  1550. separator=False)
  1551. self.align_objects_tool = AlignObjects(self)
  1552. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1553. self.edrills_tool = ToolExtractDrills(self)
  1554. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1555. self.panelize_tool = Panelize(self)
  1556. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1557. self.film_tool = Film(self)
  1558. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1559. self.paste_tool = SolderPaste(self)
  1560. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1561. self.calculator_tool = ToolCalculator(self)
  1562. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1563. self.sub_tool = ToolSub(self)
  1564. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1565. pos=self.ui.menutool, separator=True)
  1566. self.rules_tool = RulesCheck(self)
  1567. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1568. pos=self.ui.menutool, separator=False)
  1569. self.optimal_tool = ToolOptimal(self)
  1570. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1571. pos=self.ui.menutool, separator=True)
  1572. self.move_tool = ToolMove(self)
  1573. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1574. before=self.ui.menueditorigin, separator=True)
  1575. self.cutout_tool = CutOut(self)
  1576. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1577. before=self.sub_tool.menuAction)
  1578. self.ncclear_tool = NonCopperClear(self)
  1579. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1580. before=self.sub_tool.menuAction, separator=True)
  1581. self.paint_tool = ToolPaint(self)
  1582. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1583. before=self.sub_tool.menuAction, separator=True)
  1584. self.copper_thieving_tool = ToolCopperThieving(self)
  1585. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1586. pos=self.ui.menutool)
  1587. self.fiducial_tool = ToolFiducials(self)
  1588. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1589. pos=self.ui.menutool)
  1590. self.qrcode_tool = QRCode(self)
  1591. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1592. pos=self.ui.menutool)
  1593. self.punch_tool = ToolPunchGerber(self)
  1594. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1595. self.invert_tool = ToolInvertGerber(self)
  1596. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1597. self.corners_tool = ToolCorners(self)
  1598. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1599. self.transform_tool = ToolTransform(self)
  1600. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1601. pos=self.ui.menuoptions, separator=True)
  1602. self.properties_tool = Properties(self)
  1603. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1604. pos=self.ui.menuoptions)
  1605. self.pdf_tool = ToolPDF(self)
  1606. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1607. pos=self.ui.menufileimport,
  1608. separator=True)
  1609. self.image_tool = ToolImage(self)
  1610. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1611. pos=self.ui.menufileimport,
  1612. separator=True)
  1613. self.pcb_wizard_tool = PcbWizard(self)
  1614. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1615. pos=self.ui.menufileimport)
  1616. self.log.debug("Tools are installed.")
  1617. def remove_tools(self):
  1618. """
  1619. Will remove all the actions in the Tool menu.
  1620. :return: None
  1621. """
  1622. for act in self.ui.menutool.actions():
  1623. self.ui.menutool.removeAction(act)
  1624. def init_tools(self):
  1625. """
  1626. Initialize the Tool tab in the notebook side of the central widget.
  1627. Remove the actions in the Tools menu.
  1628. Instantiate again the FlatCAM tools (plugins).
  1629. All this is required when changing the layout: standard, compact etc.
  1630. :return: None
  1631. """
  1632. log.debug("init_tools()")
  1633. # delete the data currently in the Tools Tab and the Tab itself
  1634. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1635. if widget is not None:
  1636. widget.deleteLater()
  1637. self.ui.notebook.removeTab(2)
  1638. # rebuild the Tools Tab
  1639. self.ui.tool_tab = QtWidgets.QWidget()
  1640. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1641. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1642. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1643. self.ui.tool_scroll_area = VerticalScrollArea()
  1644. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1645. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1646. # first remove all of them
  1647. self.remove_tools()
  1648. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1649. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1650. '&Command Line\tS')
  1651. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1652. # third install all of them
  1653. try:
  1654. self.install_tools()
  1655. except AttributeError:
  1656. pass
  1657. self.log.debug("Tools are initialized.")
  1658. # def parse_system_fonts(self):
  1659. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1660. # 'params': []})
  1661. def connect_toolbar_signals(self):
  1662. """
  1663. Reconnect the signals to the actions in the toolbar.
  1664. This has to be done each time after the FlatCAM tools are removed/installed.
  1665. :return: None
  1666. """
  1667. # Toolbar
  1668. # File Toolbar Signals
  1669. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1670. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1671. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1672. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1673. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1674. # View Toolbar Signals
  1675. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1676. self.ui.replot_btn.triggered.connect(self.plot_all)
  1677. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1678. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1679. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1680. # Edit Toolbar Signals
  1681. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1682. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1683. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1684. self.ui.delete_btn.triggered.connect(self.on_delete)
  1685. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1686. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1687. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1688. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1689. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1690. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1691. # Scripting Toolbar Signals
  1692. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1693. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1694. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1695. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1696. # Tools Toolbar Signals
  1697. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1698. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1699. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1700. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1701. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1702. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1703. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1704. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1705. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1706. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1707. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1708. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1709. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1710. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1711. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1712. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1713. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1714. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1715. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1716. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1717. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1718. def object2editor(self):
  1719. """
  1720. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1721. :return: None
  1722. """
  1723. self.defaults.report_usage("object2editor()")
  1724. # disable the objects menu as it may interfere with the AppEditors
  1725. self.ui.menuobjects.setDisabled(True)
  1726. edited_object = self.collection.get_active()
  1727. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1728. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1729. pass
  1730. else:
  1731. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1732. return
  1733. if isinstance(edited_object, GeometryObject):
  1734. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1735. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1736. # we set the notebook to hidden
  1737. # self.ui.splitter.setSizes([0, 1])
  1738. if edited_object.multigeo is True:
  1739. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1740. if len(sel_rows) > 1:
  1741. self.inform.emit('[WARNING_NOTCL] %s' %
  1742. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1743. "is not possible.\n"
  1744. "Edit only one geometry at a time."))
  1745. # determine the tool dia of the selected tool
  1746. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1747. # now find the key in the edited_object.tools that has this tooldia
  1748. multi_tool = 1
  1749. for tool in edited_object.tools:
  1750. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1751. multi_tool = tool
  1752. break
  1753. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1754. else:
  1755. self.geo_editor.edit_fcgeometry(edited_object)
  1756. # set call source to the Editor we go into
  1757. self.call_source = 'geo_editor'
  1758. elif isinstance(edited_object, ExcellonObject):
  1759. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1760. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1761. if self.ui.splitter.sizes()[0] == 0:
  1762. self.ui.splitter.setSizes([1, 1])
  1763. self.exc_editor.edit_fcexcellon(edited_object)
  1764. # set call source to the Editor we go into
  1765. self.call_source = 'exc_editor'
  1766. elif isinstance(edited_object, GerberObject):
  1767. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1768. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1769. if self.ui.splitter.sizes()[0] == 0:
  1770. self.ui.splitter.setSizes([1, 1])
  1771. self.grb_editor.edit_fcgerber(edited_object)
  1772. # set call source to the Editor we go into
  1773. self.call_source = 'grb_editor'
  1774. # reset the following variables so the UI is built again after edit
  1775. edited_object.ui_build = False
  1776. edited_object.build_aperture_storage = False
  1777. elif isinstance(edited_object, CNCJobObject):
  1778. if self.ui.splitter.sizes()[0] == 0:
  1779. self.ui.splitter.setSizes([1, 1])
  1780. edited_object.on_edit_code_click()
  1781. return
  1782. # make sure that we can't select another object while in Editor Mode:
  1783. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1784. self.ui.project_frame.setDisabled(True)
  1785. # delete any selection shape that might be active as they are not relevant in Editor
  1786. self.delete_selection_shape()
  1787. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1788. self.ui.plot_tab_area.protectTab(0)
  1789. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1790. self.should_we_save = True
  1791. def editor2object(self, cleanup=None):
  1792. """
  1793. Transfers the Geometry or Excellon from it's editor to the current object.
  1794. :return: None
  1795. """
  1796. self.defaults.report_usage("editor2object()")
  1797. # re-enable the objects menu that was disabled on entry in Editor mode
  1798. self.ui.menuobjects.setDisabled(False)
  1799. # do not update a geometry or excellon object unless it comes out of an editor
  1800. if self.call_source != 'app':
  1801. edited_obj = self.collection.get_active()
  1802. if cleanup is None:
  1803. msgbox = QtWidgets.QMessageBox()
  1804. msgbox.setText(_("Do you want to save the edited object?"))
  1805. msgbox.setWindowTitle(_("Close Editor"))
  1806. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1807. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1808. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1809. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1810. msgbox.setDefaultButton(bt_yes)
  1811. msgbox.exec_()
  1812. response = msgbox.clickedButton()
  1813. if response == bt_yes:
  1814. # clean the Tools Tab
  1815. self.ui.tool_scroll_area.takeWidget()
  1816. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1817. self.ui.notebook.setTabText(2, "Tool")
  1818. if isinstance(edited_obj, GeometryObject):
  1819. obj_type = "Geometry"
  1820. if cleanup is None:
  1821. self.geo_editor.update_fcgeometry(edited_obj)
  1822. # self.geo_editor.update_options(edited_obj)
  1823. self.geo_editor.deactivate()
  1824. # restore GUI to the Selected TAB
  1825. # Remove anything else in the AppGUI
  1826. self.ui.tool_scroll_area.takeWidget()
  1827. # update the geo object options so it is including the bounding box values
  1828. try:
  1829. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1830. edited_obj.options['xmin'] = xmin
  1831. edited_obj.options['ymin'] = ymin
  1832. edited_obj.options['xmax'] = xmax
  1833. edited_obj.options['ymax'] = ymax
  1834. except AttributeError as e:
  1835. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1836. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1837. edited_obj.build_ui()
  1838. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1839. elif isinstance(edited_obj, GerberObject):
  1840. obj_type = "Gerber"
  1841. if cleanup is None:
  1842. self.grb_editor.update_fcgerber()
  1843. self.grb_editor.update_options(edited_obj)
  1844. self.grb_editor.deactivate_grb_editor()
  1845. # delete the old object (the source object) if it was an empty one
  1846. try:
  1847. if len(edited_obj.solid_geometry) == 0:
  1848. old_name = edited_obj.options['name']
  1849. self.collection.set_active(old_name)
  1850. self.collection.delete_active()
  1851. except TypeError:
  1852. # if the solid_geometry is a single Polygon the len() will not work
  1853. # in any case, falling here means that we have something in the solid_geometry, even if only
  1854. # a single Polygon, therefore we pass this
  1855. pass
  1856. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1857. # restore GUI to the Selected TAB
  1858. # Remove anything else in the AppGUI
  1859. self.ui.selected_scroll_area.takeWidget()
  1860. elif isinstance(edited_obj, ExcellonObject):
  1861. obj_type = "Excellon"
  1862. if cleanup is None:
  1863. self.exc_editor.update_fcexcellon(edited_obj)
  1864. # self.exc_editor.update_options(edited_obj)
  1865. self.exc_editor.deactivate()
  1866. # restore GUI to the Selected TAB
  1867. # Remove anything else in the AppGUI
  1868. self.ui.tool_scroll_area.takeWidget()
  1869. # delete the old object (the source object) if it was an empty one
  1870. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1871. old_name = edited_obj.options['name']
  1872. self.collection.delete_by_name(name=old_name)
  1873. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1874. else:
  1875. self.inform.emit('[WARNING_NOTCL] %s' %
  1876. _("Select a Gerber, Geometry or Excellon Object to update."))
  1877. return
  1878. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1879. elif response == bt_no:
  1880. # clean the Tools Tab
  1881. self.ui.tool_scroll_area.takeWidget()
  1882. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1883. self.ui.notebook.setTabText(2, "Tool")
  1884. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1885. if isinstance(edited_obj, GeometryObject):
  1886. self.geo_editor.deactivate()
  1887. edited_obj.build_ui()
  1888. elif isinstance(edited_obj, GerberObject):
  1889. self.grb_editor.deactivate_grb_editor()
  1890. edited_obj.build_ui()
  1891. elif isinstance(edited_obj, ExcellonObject):
  1892. self.exc_editor.deactivate()
  1893. edited_obj.build_ui()
  1894. else:
  1895. self.inform.emit('[WARNING_NOTCL] %s' %
  1896. _("Select a Gerber, Geometry or Excellon Object to update."))
  1897. return
  1898. elif response == bt_cancel:
  1899. return
  1900. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1901. # edited_obj.build_ui()
  1902. # Switch notebook to Selected page
  1903. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1904. else:
  1905. if isinstance(edited_obj, GeometryObject):
  1906. self.geo_editor.deactivate()
  1907. elif isinstance(edited_obj, GerberObject):
  1908. self.grb_editor.deactivate_grb_editor()
  1909. elif isinstance(edited_obj, ExcellonObject):
  1910. self.exc_editor.deactivate()
  1911. else:
  1912. self.inform.emit('[WARNING_NOTCL] %s' %
  1913. _("Select a Gerber, Geometry or Excellon Object to update."))
  1914. return
  1915. # if notebook is hidden we show it
  1916. if self.ui.splitter.sizes()[0] == 0:
  1917. self.ui.splitter.setSizes([1, 1])
  1918. # restore the call_source to app
  1919. self.call_source = 'app'
  1920. edited_obj.plot()
  1921. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1922. self.ui.plot_tab_area.protectTab(0)
  1923. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1924. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1925. self.ui.project_frame.setDisabled(False)
  1926. def get_last_folder(self):
  1927. """
  1928. Get the folder path from where the last file was opened.
  1929. :return: String, last opened folder path
  1930. """
  1931. return self.defaults["global_last_folder"]
  1932. def get_last_save_folder(self):
  1933. """
  1934. Get the folder path from where the last file was saved.
  1935. :return: String, last saved folder path
  1936. """
  1937. loc = self.defaults["global_last_save_folder"]
  1938. if loc is None:
  1939. loc = self.defaults["global_last_folder"]
  1940. if loc is None:
  1941. loc = os.path.dirname(__file__)
  1942. return loc
  1943. def info(self, msg):
  1944. """
  1945. Informs the user. Normally on the status bar, optionally
  1946. also on the shell.
  1947. :param msg: Text to write.
  1948. :return: None
  1949. """
  1950. # Type of message in brackets at the beginning of the message.
  1951. match = re.search(r"\[(.*)\](.*)", msg)
  1952. if match:
  1953. level = match.group(1)
  1954. msg_ = match.group(2)
  1955. self.ui.fcinfo.set_status(str(msg_), level=level)
  1956. if level.lower() == "error":
  1957. self.shell_message(msg, error=True, show=True)
  1958. elif level.lower() == "warning":
  1959. self.shell_message(msg, warning=True, show=True)
  1960. elif level.lower() == "error_notcl":
  1961. self.shell_message(msg, error=True, show=False)
  1962. elif level.lower() == "warning_notcl":
  1963. self.shell_message(msg, warning=True, show=False)
  1964. elif level.lower() == "success":
  1965. self.shell_message(msg, success=True, show=False)
  1966. elif level.lower() == "selected":
  1967. self.shell_message(msg, selected=True, show=False)
  1968. else:
  1969. self.shell_message(msg, show=False)
  1970. else:
  1971. self.ui.fcinfo.set_status(str(msg), level="info")
  1972. # make sure that if the message is to clear the infobar with a space
  1973. # is not printed over and over on the shell
  1974. if msg != '':
  1975. self.shell_message(msg)
  1976. def on_import_preferences(self):
  1977. """
  1978. Loads the application default settings from a saved file into
  1979. ``self.defaults`` dictionary.
  1980. :return: None
  1981. """
  1982. self.defaults.report_usage("on_import_preferences")
  1983. App.log.debug("App.on_import_preferences()")
  1984. # Show file chooser
  1985. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1986. try:
  1987. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1988. directory=self.data_path,
  1989. filter=filter_)
  1990. except TypeError:
  1991. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1992. filter=filter_)
  1993. filename = str(filename)
  1994. if filename == "":
  1995. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1996. return
  1997. # Load in the defaults from the chosen file
  1998. self.defaults.load(filename=filename)
  1999. self.preferencesUiManager.on_preferences_edited()
  2000. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2001. def on_export_preferences(self):
  2002. """
  2003. Save the defaults dictionary to a file.
  2004. :return: None
  2005. """
  2006. self.defaults.report_usage("on_export_preferences")
  2007. App.log.debug("on_export_preferences()")
  2008. # defaults_file_content = None
  2009. # Show file chooser
  2010. date = str(datetime.today()).rpartition('.')[0]
  2011. date = ''.join(c for c in date if c not in ':-')
  2012. date = date.replace(' ', '_')
  2013. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2014. try:
  2015. filename, _f = FCFileSaveDialog.get_saved_filename(
  2016. caption=_("Export FlatCAM Preferences"),
  2017. directory=self.data_path + '/preferences_' + date,
  2018. filter=filter__
  2019. )
  2020. except TypeError:
  2021. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2022. filename = str(filename)
  2023. if filename == "":
  2024. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2025. return
  2026. # Update options
  2027. self.preferencesUiManager.defaults_read_form()
  2028. self.defaults.propagate_defaults()
  2029. # Save update options
  2030. try:
  2031. self.defaults.write(filename=filename)
  2032. except Exception:
  2033. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2034. return
  2035. if self.defaults["global_open_style"] is False:
  2036. self.file_opened.emit("preferences", filename)
  2037. self.file_saved.emit("preferences", filename)
  2038. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2039. def save_to_file(self, content_to_save, txt_content):
  2040. """
  2041. Save something to a file.
  2042. :return: None
  2043. """
  2044. self.defaults.report_usage("save_to_file")
  2045. App.log.debug("save_to_file()")
  2046. self.date = str(datetime.today()).rpartition('.')[0]
  2047. self.date = ''.join(c for c in self.date if c not in ':-')
  2048. self.date = self.date.replace(' ', '_')
  2049. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2050. path_to_save = self.defaults["global_last_save_folder"] if \
  2051. self.defaults["global_last_save_folder"] is not None else self.data_path
  2052. try:
  2053. filename, _f = FCFileSaveDialog.get_saved_filename(
  2054. caption=_("Save to file"),
  2055. directory=path_to_save + '/file_' + self.date,
  2056. filter=filter__
  2057. )
  2058. except TypeError:
  2059. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2060. filename = str(filename)
  2061. if filename == "":
  2062. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2063. return
  2064. else:
  2065. try:
  2066. with open(filename, 'w') as f:
  2067. ___ = f.read()
  2068. except PermissionError:
  2069. self.inform.emit('[WARNING] %s' %
  2070. _("Permission denied, saving not possible.\n"
  2071. "Most likely another app is holding the file open and not accessible."))
  2072. return
  2073. except IOError:
  2074. App.log.debug('Creating a new file ...')
  2075. f = open(filename, 'w')
  2076. f.close()
  2077. except Exception:
  2078. e = sys.exc_info()[0]
  2079. App.log.error("Could not load the file.")
  2080. App.log.error(str(e))
  2081. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2082. return
  2083. # Save content
  2084. if filename.rpartition('.')[2].lower() == 'html':
  2085. file_content = content_to_save
  2086. else:
  2087. file_content = txt_content
  2088. try:
  2089. with open(filename, "w") as f:
  2090. f.write(file_content)
  2091. except Exception:
  2092. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2093. return
  2094. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2095. def save_geometry(self, x, y, width, height, notebook_width):
  2096. """
  2097. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2098. launch of the application.
  2099. :param x: X position of the main window
  2100. :param y: Y position of the main window
  2101. :param width: width of the main window
  2102. :param height: height of the main window
  2103. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2104. :return: None
  2105. """
  2106. self.defaults["global_def_win_x"] = x
  2107. self.defaults["global_def_win_y"] = y
  2108. self.defaults["global_def_win_w"] = width
  2109. self.defaults["global_def_win_h"] = height
  2110. self.defaults["global_def_notebook_width"] = notebook_width
  2111. self.preferencesUiManager.save_defaults()
  2112. def register_recent(self, kind, filename):
  2113. """
  2114. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2115. dictionary.
  2116. :param kind: type of file that was opened
  2117. :param filename: the path and file name for the file that was opened
  2118. :return:
  2119. """
  2120. self.log.debug("register_recent()")
  2121. self.log.debug(" %s" % kind)
  2122. self.log.debug(" %s" % filename)
  2123. record = {'kind': str(kind), 'filename': str(filename)}
  2124. if record in self.recent:
  2125. return
  2126. if record in self.recent_projects:
  2127. return
  2128. if record['kind'] == 'project':
  2129. self.recent_projects.insert(0, record)
  2130. else:
  2131. self.recent.insert(0, record)
  2132. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2133. self.recent.pop()
  2134. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2135. self.recent_projects.pop()
  2136. try:
  2137. f = open(self.data_path + '/recent.json', 'w')
  2138. except IOError:
  2139. App.log.error("Failed to open recent items file for writing.")
  2140. self.inform.emit('[ERROR_NOTCL] %s' %
  2141. _('Failed to open recent files file for writing.'))
  2142. return
  2143. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2144. f.close()
  2145. try:
  2146. fp = open(self.data_path + '/recent_projects.json', 'w')
  2147. except IOError:
  2148. App.log.error("Failed to open recent items file for writing.")
  2149. self.inform.emit('[ERROR_NOTCL] %s' %
  2150. _('Failed to open recent projects file for writing.'))
  2151. return
  2152. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2153. fp.close()
  2154. # Re-build the recent items menu
  2155. self.setup_recent_items()
  2156. def on_about(self):
  2157. """
  2158. Displays the "about" dialog found in the Menu --> Help.
  2159. :return: None
  2160. """
  2161. self.defaults.report_usage("on_about")
  2162. version = self.version
  2163. version_date = self.version_date
  2164. beta = self.beta
  2165. class AboutDialog(QtWidgets.QDialog):
  2166. def __init__(self, app, parent=None):
  2167. QtWidgets.QDialog.__init__(self, parent)
  2168. self.app = app
  2169. # Icon and title
  2170. self.setWindowIcon(parent.app_icon)
  2171. self.setWindowTitle(_("About FlatCAM"))
  2172. self.resize(600, 200)
  2173. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2174. # self.setStyleSheet(
  2175. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2176. # "background-attachment: fixed"
  2177. # )
  2178. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2179. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2180. # palette = QtGui.QPalette()
  2181. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2182. # self.setPalette(palette)
  2183. logo = QtWidgets.QLabel()
  2184. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2185. title = QtWidgets.QLabel(
  2186. "<font size=8><B>FlatCAM</B></font><BR>"
  2187. "{title}<BR>"
  2188. "<BR>"
  2189. "<BR>"
  2190. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2191. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2192. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2193. "<B>{issue}</B></a><BR>".format(
  2194. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2195. devel=_("Development"),
  2196. down=_("DOWNLOAD"),
  2197. issue=_("Issue tracker"))
  2198. )
  2199. title.setOpenExternalLinks(True)
  2200. closebtn = QtWidgets.QPushButton(_("Close"))
  2201. tab_widget = QtWidgets.QTabWidget()
  2202. description_label = QtWidgets.QLabel(
  2203. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2204. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2205. version=version,
  2206. beta=('BETA' if beta else ''),
  2207. date=version_date,
  2208. arch=platform.architecture()[0])
  2209. )
  2210. description_label.setOpenExternalLinks(True)
  2211. lic_lbl_header = QtWidgets.QLabel(
  2212. '%s:<br>%s<br>' % (
  2213. _('Licensed under the MIT license'),
  2214. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2215. "http://www.opensource.org/licenses/mit-license.php</a>"
  2216. )
  2217. )
  2218. lic_lbl_header.setOpenExternalLinks(True)
  2219. lic_lbl_body = QtWidgets.QLabel(
  2220. _(
  2221. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2222. 'of this software and associated documentation files (the "Software"), to deal\n'
  2223. 'in the Software without restriction, including without limitation the rights\n'
  2224. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2225. 'copies of the Software, and to permit persons to whom the Software is\n'
  2226. 'furnished to do so, subject to the following conditions:\n\n'
  2227. 'The above copyright notice and this permission notice shall be included in\n'
  2228. 'all copies or substantial portions of the Software.\n\n'
  2229. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2230. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2231. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2232. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2233. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2234. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2235. 'THE SOFTWARE.'
  2236. )
  2237. )
  2238. attributions_label = QtWidgets.QLabel(
  2239. _(
  2240. 'Some of the icons used are from the following sources:<br>'
  2241. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2242. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2243. 'title="Flaticon">www.flaticon.com</a></div>'
  2244. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2245. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2246. )
  2247. )
  2248. attributions_label.setOpenExternalLinks(True)
  2249. # layouts
  2250. layout1 = QtWidgets.QVBoxLayout()
  2251. layout1_1 = QtWidgets.QHBoxLayout()
  2252. layout1_2 = QtWidgets.QHBoxLayout()
  2253. layout2 = QtWidgets.QHBoxLayout()
  2254. layout3 = QtWidgets.QHBoxLayout()
  2255. self.setLayout(layout1)
  2256. layout1.addLayout(layout1_1)
  2257. layout1.addLayout(layout1_2)
  2258. layout1.addLayout(layout2)
  2259. layout1.addLayout(layout3)
  2260. layout1_1.addStretch()
  2261. layout1_1.addWidget(description_label)
  2262. layout1_2.addWidget(tab_widget)
  2263. self.splash_tab = QtWidgets.QWidget()
  2264. self.splash_tab.setObjectName("splash_about")
  2265. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2266. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2267. tab_widget.addTab(self.splash_tab, _("Splash"))
  2268. self.programmmers_tab = QtWidgets.QWidget()
  2269. self.programmmers_tab.setObjectName("programmers_about")
  2270. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2271. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2272. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2273. self.translators_tab = QtWidgets.QWidget()
  2274. self.translators_tab.setObjectName("translators_about")
  2275. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2276. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2277. tab_widget.addTab(self.translators_tab, _("Translators"))
  2278. self.license_tab = QtWidgets.QWidget()
  2279. self.license_tab.setObjectName("license_about")
  2280. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2281. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2282. tab_widget.addTab(self.license_tab, _("License"))
  2283. self.attributions_tab = QtWidgets.QWidget()
  2284. self.attributions_tab.setObjectName("attributions_about")
  2285. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2286. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2287. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2288. self.splash_tab_layout.addWidget(logo, stretch=0)
  2289. self.splash_tab_layout.addWidget(title, stretch=1)
  2290. pal = QtGui.QPalette()
  2291. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2292. self.prog_grid_lay = QtWidgets.QGridLayout()
  2293. self.prog_grid_lay.setHorizontalSpacing(20)
  2294. self.prog_grid_lay.setColumnStretch(0, 0)
  2295. self.prog_grid_lay.setColumnStretch(2, 1)
  2296. prog_widget = QtWidgets.QWidget()
  2297. prog_widget.setLayout(self.prog_grid_lay)
  2298. prog_scroll = QtWidgets.QScrollArea()
  2299. prog_scroll.setWidget(prog_widget)
  2300. prog_scroll.setWidgetResizable(True)
  2301. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2302. prog_scroll.setPalette(pal)
  2303. self.programmmers_tab_layout.addWidget(prog_scroll)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2351. self.translator_grid_lay = QtWidgets.QGridLayout()
  2352. self.translator_grid_lay.setColumnStretch(0, 0)
  2353. self.translator_grid_lay.setColumnStretch(1, 0)
  2354. self.translator_grid_lay.setColumnStretch(2, 1)
  2355. self.translator_grid_lay.setColumnStretch(3, 0)
  2356. # trans_widget = QtWidgets.QWidget()
  2357. # trans_widget.setLayout(self.translator_grid_lay)
  2358. # self.translators_tab_layout.addWidget(trans_widget)
  2359. # self.translators_tab_layout.addStretch()
  2360. trans_widget = QtWidgets.QWidget()
  2361. trans_widget.setLayout(self.translator_grid_lay)
  2362. trans_scroll = QtWidgets.QScrollArea()
  2363. trans_scroll.setWidget(trans_widget)
  2364. trans_scroll.setWidgetResizable(True)
  2365. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2366. trans_scroll.setPalette(pal)
  2367. self.translators_tab_layout.addWidget(trans_scroll)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2401. self.translator_grid_lay.setColumnStretch(0, 0)
  2402. self.translators_tab_layout.addStretch()
  2403. self.license_tab_layout.addWidget(lic_lbl_header)
  2404. self.license_tab_layout.addWidget(lic_lbl_body)
  2405. self.license_tab_layout.addStretch()
  2406. self.attributions_tab_layout.addWidget(attributions_label)
  2407. self.attributions_tab_layout.addStretch()
  2408. layout3.addStretch()
  2409. layout3.addWidget(closebtn)
  2410. closebtn.clicked.connect(self.accept)
  2411. AboutDialog(app=self, parent=self.ui).exec_()
  2412. def install_bookmarks(self, book_dict=None):
  2413. """
  2414. Install the bookmarks actions in the Help menu -> Bookmarks
  2415. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2416. :return: None
  2417. """
  2418. if book_dict is None:
  2419. self.defaults["global_bookmarks"].update(
  2420. {
  2421. '1': ['FlatCAM', "http://flatcam.org"],
  2422. '2': ['Backup Site', ""]
  2423. }
  2424. )
  2425. else:
  2426. self.defaults["global_bookmarks"].clear()
  2427. self.defaults["global_bookmarks"].update(book_dict)
  2428. # first try to disconnect if somehow they get connected from elsewhere
  2429. for act in self.ui.menuhelp_bookmarks.actions():
  2430. try:
  2431. act.triggered.disconnect()
  2432. except TypeError:
  2433. pass
  2434. # clear all actions except the last one who is the Bookmark manager
  2435. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2436. pass
  2437. else:
  2438. self.ui.menuhelp_bookmarks.removeAction(act)
  2439. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2440. if self.defaults["global_bookmarks"]:
  2441. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2442. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2443. # the JSON is first making the keys as strings (therefore I have to use strings too
  2444. # or do the conversion :(
  2445. # )
  2446. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2447. # the '10' entry jsut after '1' therefore ordering as strings
  2448. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2449. key=lambda x: int(x[0]))
  2450. for entry, bookmark in sorted_bookmarks:
  2451. title = bookmark[0]
  2452. weblink = bookmark[1]
  2453. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2454. act.setText(title)
  2455. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2456. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2457. if title == 'Backup Site' and weblink == "":
  2458. act.triggered.connect(self.on_backup_site)
  2459. else:
  2460. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2461. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2462. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2463. def on_bookmarks_manager(self):
  2464. """
  2465. Adds the bookmark manager in a Tab in Plot Area
  2466. :return:
  2467. """
  2468. for idx in range(self.ui.plot_tab_area.count()):
  2469. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2470. # there can be only one instance of Bookmark Manager at one time
  2471. return
  2472. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2473. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2474. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2475. # add the tab if it was closed
  2476. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2477. # delete the absolute and relative position and messages in the infobar
  2478. self.ui.position_label.setText("")
  2479. # self.ui.rel_position_label.setText("")
  2480. # Switch plot_area to preferences page
  2481. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2482. def on_backup_site(self):
  2483. msgbox = QtWidgets.QMessageBox()
  2484. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2485. "1. FlatCAM.org website is down\n"
  2486. "2. Someone forked FlatCAM project and wants to point\n"
  2487. "to his own website\n\n"
  2488. "If you can't get any informations about FlatCAM beta\n"
  2489. "use the YouTube channel link from the Help menu."))
  2490. msgbox.setWindowTitle(_("Alternative website"))
  2491. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2492. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2493. msgbox.setDefaultButton(bt_yes)
  2494. msgbox.exec_()
  2495. # response = msgbox.clickedButton()
  2496. def on_file_savedefaults(self):
  2497. """
  2498. Callback for menu item File->Save Defaults. Saves application default options
  2499. ``self.defaults`` to current_defaults.FlatConfig.
  2500. :return: None
  2501. """
  2502. self.preferencesUiManager.save_defaults()
  2503. def final_save(self):
  2504. """
  2505. Callback for doing a preferences save to file whenever the application is about to quit.
  2506. If the project has changes, it will ask the user to save the project.
  2507. :return: None
  2508. """
  2509. if self.save_in_progress:
  2510. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2511. return
  2512. if self.should_we_save and self.collection.get_list():
  2513. msgbox = QtWidgets.QMessageBox()
  2514. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2515. "\n"
  2516. "Do you want to Save the project?"))
  2517. msgbox.setWindowTitle(_("Save changes"))
  2518. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2519. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2520. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2521. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2522. msgbox.setDefaultButton(bt_yes)
  2523. msgbox.exec_()
  2524. response = msgbox.clickedButton()
  2525. if response == bt_yes:
  2526. try:
  2527. self.trayIcon.hide()
  2528. except Exception:
  2529. pass
  2530. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2531. elif response == bt_no:
  2532. try:
  2533. self.trayIcon.hide()
  2534. except Exception:
  2535. pass
  2536. self.quit_application()
  2537. elif response == bt_cancel:
  2538. return
  2539. else:
  2540. try:
  2541. self.trayIcon.hide()
  2542. except Exception:
  2543. pass
  2544. self.quit_application()
  2545. def quit_application(self):
  2546. """
  2547. Called (as a pyslot or not) when the application is quit.
  2548. :return: None
  2549. """
  2550. self.preferencesUiManager.save_defaults(silent=True)
  2551. log.debug("App.quit_application() --> App Defaults saved.")
  2552. if self.cmd_line_headless != 1:
  2553. # save app state to file
  2554. stgs = QSettings("Open Source", "FlatCAM")
  2555. stgs.setValue('saved_gui_state', self.ui.saveState())
  2556. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2557. stgs.setValue(
  2558. 'language',
  2559. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2560. )
  2561. stgs.setValue(
  2562. 'notebook_font_size',
  2563. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2564. )
  2565. stgs.setValue(
  2566. 'axis_font_size',
  2567. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2568. )
  2569. stgs.setValue(
  2570. 'textbox_font_size',
  2571. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2572. )
  2573. stgs.setValue(
  2574. 'hud_font_size',
  2575. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2576. )
  2577. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2578. stgs.setValue(
  2579. 'machinist',
  2580. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2581. )
  2582. # This will write the setting to the platform specific storage.
  2583. del stgs
  2584. log.debug("App.quit_application() --> App UI state saved.")
  2585. # try to quit the Socket opened by ArgsThread class
  2586. try:
  2587. self.new_launch.stop.emit()
  2588. except Exception as err:
  2589. log.debug("App.quit_application() --> %s" % str(err))
  2590. # try to quit the QThread that run ArgsThread class
  2591. try:
  2592. self.th.quit()
  2593. except Exception as e:
  2594. log.debug("App.quit_application() --> %s" % str(e))
  2595. # terminate workers
  2596. self.workers.__del__()
  2597. # quit app by signalling for self.kill_app() method
  2598. # self.close_app_signal.emit()
  2599. QtWidgets.qApp.quit()
  2600. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2601. # we use the following command
  2602. minor_v = sys.version_info.minor
  2603. if minor_v < 8:
  2604. sys.exit(0)
  2605. else:
  2606. os._exit(0) # fix to work with Python 3.8
  2607. @staticmethod
  2608. def kill_app():
  2609. QtWidgets.qApp.quit()
  2610. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2611. # we use the following command
  2612. sys.exit(0)
  2613. def on_portable_checked(self, state):
  2614. """
  2615. Callback called when the checkbox in Preferences GUI is checked.
  2616. It will set the application as portable by creating the preferences and recent files in the
  2617. 'config' folder found in the FlatCAM installation folder.
  2618. :param state: boolean, the state of the checkbox when clicked/checked
  2619. :return:
  2620. """
  2621. line_no = 0
  2622. data = None
  2623. if sys.platform != 'win32':
  2624. # this won't work in Linux or MacOS
  2625. return
  2626. # test if the app was frozen and choose the path for the configuration file
  2627. if getattr(sys, "frozen", False) is True:
  2628. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2629. else:
  2630. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2631. config_file = current_data_path + '\\configuration.txt'
  2632. try:
  2633. with open(config_file, 'r') as f:
  2634. try:
  2635. data = f.readlines()
  2636. except Exception as e:
  2637. log.debug('App.__init__() -->%s' % str(e))
  2638. return
  2639. except FileNotFoundError:
  2640. pass
  2641. for line in data:
  2642. line = line.strip('\n')
  2643. param = str(line).rpartition('=')
  2644. if param[0] == 'portable':
  2645. break
  2646. line_no += 1
  2647. if state:
  2648. data[line_no] = 'portable=True\n'
  2649. # create the new defauults files
  2650. # create current_defaults.FlatConfig file if there is none
  2651. try:
  2652. f = open(current_data_path + '/current_defaults.FlatConfig')
  2653. f.close()
  2654. except IOError:
  2655. App.log.debug('Creating empty current_defaults.FlatConfig')
  2656. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2657. json.dump({}, f)
  2658. f.close()
  2659. # create factory_defaults.FlatConfig file if there is none
  2660. try:
  2661. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2662. f.close()
  2663. except IOError:
  2664. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2665. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2666. json.dump({}, f)
  2667. f.close()
  2668. try:
  2669. f = open(current_data_path + '/recent.json')
  2670. f.close()
  2671. except IOError:
  2672. App.log.debug('Creating empty recent.json')
  2673. f = open(current_data_path + '/recent.json', 'w')
  2674. json.dump([], f)
  2675. f.close()
  2676. try:
  2677. fp = open(current_data_path + '/recent_projects.json')
  2678. fp.close()
  2679. except IOError:
  2680. App.log.debug('Creating empty recent_projects.json')
  2681. fp = open(current_data_path + '/recent_projects.json', 'w')
  2682. json.dump([], fp)
  2683. fp.close()
  2684. # save the current defaults to the new defaults file
  2685. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2686. else:
  2687. data[line_no] = 'portable=False\n'
  2688. with open(config_file, 'w') as f:
  2689. f.writelines(data)
  2690. def on_register_files(self, obj_type=None):
  2691. """
  2692. Called whenever there is a need to register file extensions with FlatCAM.
  2693. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2694. :param obj_type: the type of object to be register for.
  2695. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2696. :return: None
  2697. """
  2698. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2699. new_reg_path = 'Software\\Classes\\'
  2700. # find if the current user is admin
  2701. try:
  2702. is_admin = os.getuid() == 0
  2703. except AttributeError:
  2704. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2705. if is_admin is True:
  2706. root_path = winreg.HKEY_LOCAL_MACHINE
  2707. else:
  2708. root_path = winreg.HKEY_CURRENT_USER
  2709. # create the keys
  2710. def set_reg(name, root_pth, new_reg_path, value):
  2711. try:
  2712. winreg.CreateKey(root_pth, new_reg_path)
  2713. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2714. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2715. return True
  2716. except WindowsError:
  2717. return False
  2718. # delete key in registry
  2719. def delete_reg(root_pth, reg_path, key_to_del):
  2720. key_to_del_path = reg_path + key_to_del
  2721. try:
  2722. winreg.DeleteKey(root_pth, key_to_del_path)
  2723. return True
  2724. except WindowsError:
  2725. return False
  2726. if obj_type is None or obj_type == 'excellon':
  2727. exc_list = \
  2728. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2729. exc_list = [x for x in exc_list if x != '']
  2730. # register all keys in the Preferences window
  2731. for ext in exc_list:
  2732. new_k = new_reg_path + '.%s' % ext
  2733. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2734. # and unregister those that are no longer in the Preferences windows but are in the file
  2735. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2736. if ext not in exc_list:
  2737. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2738. # now write the updated extensions to the self.defaults
  2739. # new_ext = ''
  2740. # for ext in exc_list:
  2741. # new_ext = new_ext + ext + ', '
  2742. # self.defaults["fa_excellon"] = new_ext
  2743. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2744. if obj_type is None or obj_type == 'gcode':
  2745. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2746. gco_list = [x for x in gco_list if x != '']
  2747. # register all keys in the Preferences window
  2748. for ext in gco_list:
  2749. new_k = new_reg_path + '.%s' % ext
  2750. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2751. # and unregister those that are no longer in the Preferences windows but are in the file
  2752. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2753. if ext not in gco_list:
  2754. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2755. # now write the updated extensions to the self.defaults
  2756. # new_ext = ''
  2757. # for ext in gco_list:
  2758. # new_ext = new_ext + ext + ', '
  2759. # self.defaults["fa_gcode"] = new_ext
  2760. self.inform.emit('[success] %s' %
  2761. _("Selected GCode file extensions registered with FlatCAM."))
  2762. if obj_type is None or obj_type == 'gerber':
  2763. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2764. grb_list = [x for x in grb_list if x != '']
  2765. # register all keys in the Preferences window
  2766. for ext in grb_list:
  2767. new_k = new_reg_path + '.%s' % ext
  2768. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2769. # and unregister those that are no longer in the Preferences windows but are in the file
  2770. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2771. if ext not in grb_list:
  2772. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2773. # now write the updated extensions to the self.defaults
  2774. # new_ext = ''
  2775. # for ext in grb_list:
  2776. # new_ext = new_ext + ext + ', '
  2777. # self.defaults["fa_gerber"] = new_ext
  2778. self.inform.emit('[success] %s' %
  2779. _("Selected Gerber file extensions registered with FlatCAM."))
  2780. def add_extension(self, ext_type):
  2781. """
  2782. Add a file extension to the list for a specific object
  2783. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2784. :return:
  2785. """
  2786. if ext_type == 'excellon':
  2787. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2788. if new_ext == '':
  2789. return
  2790. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2791. if new_ext in old_val:
  2792. return
  2793. old_val.append(new_ext)
  2794. old_val.sort()
  2795. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2796. if ext_type == 'gcode':
  2797. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2798. if new_ext == '':
  2799. return
  2800. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2801. if new_ext in old_val:
  2802. return
  2803. old_val.append(new_ext)
  2804. old_val.sort()
  2805. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2806. if ext_type == 'gerber':
  2807. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2808. if new_ext == '':
  2809. return
  2810. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2811. if new_ext in old_val:
  2812. return
  2813. old_val.append(new_ext)
  2814. old_val.sort()
  2815. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2816. if ext_type == 'keyword':
  2817. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2818. if new_kw == '':
  2819. return
  2820. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2821. if new_kw in old_val:
  2822. return
  2823. old_val.append(new_kw)
  2824. old_val.sort()
  2825. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2826. # update the self.myKeywords so the model is updated
  2827. self.autocomplete_kw_list = \
  2828. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2829. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2830. self.shell._edit.set_model_data(self.myKeywords)
  2831. def del_extension(self, ext_type):
  2832. """
  2833. Remove a file extension from the list for a specific object
  2834. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2835. :return:
  2836. """
  2837. if ext_type == 'excellon':
  2838. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2839. if new_ext == '':
  2840. return
  2841. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2842. if new_ext not in old_val:
  2843. return
  2844. old_val.remove(new_ext)
  2845. old_val.sort()
  2846. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2847. if ext_type == 'gcode':
  2848. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2849. if new_ext == '':
  2850. return
  2851. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2852. if new_ext not in old_val:
  2853. return
  2854. old_val.remove(new_ext)
  2855. old_val.sort()
  2856. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2857. if ext_type == 'gerber':
  2858. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2859. if new_ext == '':
  2860. return
  2861. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2862. if new_ext not in old_val:
  2863. return
  2864. old_val.remove(new_ext)
  2865. old_val.sort()
  2866. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2867. if ext_type == 'keyword':
  2868. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2869. if new_kw == '':
  2870. return
  2871. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2872. if new_kw not in old_val:
  2873. return
  2874. old_val.remove(new_kw)
  2875. old_val.sort()
  2876. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2877. # update the self.myKeywords so the model is updated
  2878. self.autocomplete_kw_list = \
  2879. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2880. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2881. self.shell._edit.set_model_data(self.myKeywords)
  2882. def restore_extensions(self, ext_type):
  2883. """
  2884. Restore all file extensions associations with FlatCAM, for a specific object
  2885. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2886. :return:
  2887. """
  2888. if ext_type == 'excellon':
  2889. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2890. # for the ability to open Excellon files with .txt extension
  2891. new_exc_list = deepcopy(self.exc_list)
  2892. try:
  2893. new_exc_list.remove('txt')
  2894. except ValueError:
  2895. pass
  2896. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2897. if ext_type == 'gcode':
  2898. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2899. if ext_type == 'gerber':
  2900. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2901. if ext_type == 'keyword':
  2902. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2903. # update the self.myKeywords so the model is updated
  2904. self.autocomplete_kw_list = self.default_keywords
  2905. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2906. self.shell._edit.set_model_data(self.myKeywords)
  2907. def delete_all_extensions(self, ext_type):
  2908. """
  2909. Delete all file extensions associations with FlatCAM, for a specific object
  2910. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2911. :return:
  2912. """
  2913. if ext_type == 'excellon':
  2914. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2915. if ext_type == 'gcode':
  2916. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2917. if ext_type == 'gerber':
  2918. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2919. if ext_type == 'keyword':
  2920. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2921. # update the self.myKeywords so the model is updated
  2922. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2923. self.shell._edit.set_model_data(self.myKeywords)
  2924. def on_edit_join(self, name=None):
  2925. """
  2926. Callback for Edit->Join. Joins the selected geometry objects into
  2927. a new one.
  2928. :return: None
  2929. """
  2930. self.defaults.report_usage("on_edit_join()")
  2931. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2932. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2933. geo_type_set = set()
  2934. objs = self.collection.get_selected()
  2935. if len(objs) < 2:
  2936. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2937. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2938. return 'fail'
  2939. for obj in objs:
  2940. geo_type_set.add(obj.multigeo)
  2941. # if len(geo_type_list) == 1 means that all list elements are the same
  2942. if len(geo_type_set) != 1:
  2943. self.inform.emit('[ERROR] %s' %
  2944. _("Failed join. The Geometry objects are of different types.\n"
  2945. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2946. "convert from one to another and retry joining \n"
  2947. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2948. "the result may not be what was expected. \n"
  2949. "Check the generated GCODE."))
  2950. return
  2951. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2952. if True in geo_type_set:
  2953. def initialize(geo_obj, app):
  2954. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2955. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2956. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2957. for v in geo_obj.tools.values():
  2958. v['data']['name'] = obj_name_multi
  2959. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2960. else:
  2961. def initialize(geo_obj, app):
  2962. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2963. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2964. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2965. for v in geo_obj.tools.values():
  2966. v['data']['name'] = obj_name_single
  2967. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2968. self.should_we_save = True
  2969. def on_edit_join_exc(self):
  2970. """
  2971. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2972. a new Excellon.
  2973. :return: None
  2974. """
  2975. self.defaults.report_usage("on_edit_join_exc()")
  2976. objs = self.collection.get_selected()
  2977. for obj in objs:
  2978. if not isinstance(obj, ExcellonObject):
  2979. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  2980. return
  2981. if len(objs) < 2:
  2982. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2983. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2984. return 'fail'
  2985. def initialize(exc_obj, app):
  2986. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  2987. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  2988. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  2989. self.should_we_save = True
  2990. def on_edit_join_grb(self):
  2991. """
  2992. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2993. a new Gerber object.
  2994. :return: None
  2995. """
  2996. self.defaults.report_usage("on_edit_join_grb()")
  2997. objs = self.collection.get_selected()
  2998. for obj in objs:
  2999. if not isinstance(obj, GerberObject):
  3000. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3001. return
  3002. if len(objs) < 2:
  3003. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3004. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3005. return 'fail'
  3006. def initialize(grb_obj, app):
  3007. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3008. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3009. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3010. self.should_we_save = True
  3011. def on_convert_singlegeo_to_multigeo(self):
  3012. """
  3013. Called for converting a Geometry object from single-geo to multi-geo.
  3014. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3015. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3016. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3017. the solid-geometry of that tool.
  3018. :return: None
  3019. """
  3020. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3021. obj = self.collection.get_active()
  3022. if obj is None:
  3023. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3024. return
  3025. if not isinstance(obj, GeometryObject):
  3026. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3027. return
  3028. obj.multigeo = True
  3029. for tooluid, dict_value in obj.tools.items():
  3030. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3031. if not isinstance(obj.solid_geometry, list):
  3032. obj.solid_geometry = [obj.solid_geometry]
  3033. # obj.solid_geometry[:] = []
  3034. obj.plot()
  3035. self.should_we_save = True
  3036. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3037. def on_convert_multigeo_to_singlegeo(self):
  3038. """
  3039. Called for converting a Geometry object from multi-geo to single-geo.
  3040. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3041. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3042. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3043. the solid-geometry of that tool.
  3044. :return: None
  3045. """
  3046. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3047. obj = self.collection.get_active()
  3048. if obj is None:
  3049. self.inform.emit('[ERROR_NOTCL] %s' %
  3050. _("Failed. Select a Geometry Object and try again."))
  3051. return
  3052. if not isinstance(obj, GeometryObject):
  3053. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3054. (_("Expected a GeometryObject, got"), type(obj)))
  3055. return
  3056. obj.multigeo = False
  3057. total_solid_geometry = []
  3058. for tooluid, dict_value in obj.tools.items():
  3059. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3060. # clear the original geometry
  3061. dict_value['solid_geometry'][:] = []
  3062. obj.solid_geometry = deepcopy(total_solid_geometry)
  3063. obj.plot()
  3064. self.should_we_save = True
  3065. self.inform.emit('[success] %s' %
  3066. _("A Geometry object was converted to SingleGeo type."))
  3067. def on_defaults_dict_change(self, field):
  3068. """
  3069. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3070. Edit -> Preferences tab window.
  3071. :param field: the key of the self.defaults dictionary that was changed.
  3072. :return: None
  3073. """
  3074. self.preferencesUiManager.defaults_write_form_field(field=field)
  3075. if field == "units":
  3076. self.set_screen_units(self.defaults['units'])
  3077. def set_screen_units(self, units):
  3078. """
  3079. Set the FlatCAM units on the status bar.
  3080. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3081. :return: None
  3082. """
  3083. self.ui.units_label.setText("[" + units.lower() + "]")
  3084. def on_toggle_units_click(self):
  3085. try:
  3086. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3087. except (TypeError, AttributeError):
  3088. pass
  3089. if self.defaults["units"] == 'MM':
  3090. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3091. else:
  3092. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3093. self.on_toggle_units(no_pref=True)
  3094. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3095. lambda: self.on_toggle_units(no_pref=False))
  3096. def on_toggle_units(self, no_pref=False):
  3097. """
  3098. Callback for the Units radio-button change in the Preferences tab.
  3099. Changes the application's default units adn for the project too.
  3100. If changing the project's units, the change propagates to all of
  3101. the objects in the project.
  3102. :return: None
  3103. """
  3104. self.defaults.report_usage("on_toggle_units")
  3105. if self.toggle_units_ignore:
  3106. return
  3107. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3108. # If option is the same, then ignore
  3109. if new_units == self.defaults["units"].upper():
  3110. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3111. return
  3112. # Keys in self.defaults for which to scale their values
  3113. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3114. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3115. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3116. "gerber_editor_ma_high",
  3117. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3118. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3119. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3120. "excellon_feedrate_probe", "excellon_milling_dia",
  3121. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3122. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3123. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3124. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3125. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3126. "geometry_extracut_length", "geometry_z_pdepth",
  3127. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3128. 'cncjob_tooldia',
  3129. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3130. "tools_paintnewdia",
  3131. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3132. "tools_nccnewdia", "tools_ncc_offset_value",
  3133. "tools_2sided_drilldia",
  3134. "tools_film_boundary", "tools_film_scale_stroke",
  3135. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3136. "tools_cutout_depthperpass",
  3137. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3138. "tools_panelize_spacing_rows",
  3139. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3140. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3141. "tools_transform_buffer_dis",
  3142. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3143. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3144. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3145. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3146. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3147. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3148. "tools_cr_h2h_val", "tools_cr_dh_val",
  3149. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3150. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3151. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3152. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3153. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3154. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3155. "tools_copper_thieving_mask_clearance",
  3156. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3157. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3158. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3159. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3160. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3161. "tools_invert_margin",
  3162. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3163. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3164. def scale_defaults(sfactor):
  3165. for dim in dimensions:
  3166. if dim in [
  3167. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3168. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3169. 'tools_transform_mirror_point'
  3170. ]:
  3171. if self.defaults[dim] is None or self.defaults[dim] == '':
  3172. continue
  3173. try:
  3174. coordinates = self.defaults[dim].split(",")
  3175. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3176. coords_xy[0] *= sfactor
  3177. coords_xy[1] *= sfactor
  3178. self.defaults[dim] = "%.*f, %.*f" % (
  3179. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3180. except Exception as e:
  3181. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3182. elif dim in [
  3183. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3184. ]:
  3185. if self.defaults[dim] is None or self.defaults[dim] == '':
  3186. continue
  3187. try:
  3188. self.defaults[dim] = float(self.defaults[dim])
  3189. tools_diameters = [self.defaults[dim]]
  3190. except ValueError:
  3191. try:
  3192. tools_string = self.defaults[dim].split(",")
  3193. tools_diameters = [eval(a) for a in tools_string if a != '']
  3194. except Exception as e:
  3195. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3196. continue
  3197. self.defaults[dim] = ''
  3198. td_len = len(tools_diameters)
  3199. if td_len > 1:
  3200. for t in range(td_len):
  3201. tools_diameters[t] *= sfactor
  3202. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3203. else:
  3204. tools_diameters[0] *= sfactor
  3205. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3206. elif dim in ['global_gridx', 'global_gridy']:
  3207. # format the number of decimals to the one specified in self.decimals
  3208. try:
  3209. val = float(self.defaults[dim]) * sfactor
  3210. except Exception as e:
  3211. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3212. continue
  3213. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3214. else:
  3215. # the number of decimals for the rest is kept unchanged
  3216. if self.defaults[dim]:
  3217. try:
  3218. val = float(self.defaults[dim]) * sfactor
  3219. except Exception as e:
  3220. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3221. continue
  3222. self.defaults[dim] = val
  3223. # The scaling factor depending on choice of units.
  3224. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3225. # Changing project units. Warn user.
  3226. msgbox = QtWidgets.QMessageBox()
  3227. msgbox.setWindowTitle(_("Toggle Units"))
  3228. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3229. msgbox.setText(_("Changing the units of the project\n"
  3230. "will scale all objects.\n\n"
  3231. "Do you want to continue?"))
  3232. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3233. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3234. msgbox.setDefaultButton(bt_ok)
  3235. msgbox.exec_()
  3236. response = msgbox.clickedButton()
  3237. if response == bt_ok:
  3238. if no_pref is False:
  3239. self.preferencesUiManager.defaults_read_form()
  3240. scale_defaults(factor)
  3241. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3242. self.defaults["units"] = new_units
  3243. # update the defaults from form, some may assume that the conversion is enough and it's not
  3244. self.on_options_app2project()
  3245. # update the objects
  3246. for obj in self.collection.get_list():
  3247. obj.convert_units(new_units)
  3248. # make that the properties stored in the object are also updated
  3249. self.app_obj.object_changed.emit(obj)
  3250. # rebuild the object UI
  3251. obj.build_ui()
  3252. # change this only if the workspace is active
  3253. if self.defaults['global_workspace'] is True:
  3254. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3255. # adjust the grid values on the main toolbar
  3256. val_x = float(self.defaults['global_gridx']) * factor
  3257. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3258. current = self.collection.get_active()
  3259. if current is not None:
  3260. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3261. if not isinstance(current, GeometryObject):
  3262. current.to_form()
  3263. # replot all objects
  3264. self.plot_all()
  3265. # set the status labels to reflect the current FlatCAM units
  3266. self.set_screen_units(new_units)
  3267. # signal to the app that we changed the object properties and it should save the project
  3268. self.should_we_save = True
  3269. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3270. else:
  3271. # Undo toggling
  3272. self.toggle_units_ignore = True
  3273. if self.defaults['units'].upper() == 'MM':
  3274. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3275. else:
  3276. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3277. self.toggle_units_ignore = False
  3278. # store the grid values so they are not changed in the next step
  3279. val_x = float(self.defaults['global_gridx'])
  3280. val_y = float(self.defaults['global_gridy'])
  3281. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3282. self.preferencesUiManager.defaults_read_form()
  3283. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3284. # in self.defaults from the GUI elements but
  3285. # I don't want it for the grid values, so I update them here
  3286. self.defaults['global_gridx'] = val_x
  3287. self.defaults['global_gridy'] = val_y
  3288. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3289. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3290. def on_toggle_axis(self):
  3291. self.defaults.report_usage("on_toggle_axis()")
  3292. if self.toggle_axis is False:
  3293. if self.is_legacy is False:
  3294. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3295. parent=self.plotcanvas.view.scene)
  3296. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3297. parent=self.plotcanvas.view.scene)
  3298. else:
  3299. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3300. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3301. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3302. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3303. self.plotcanvas.canvas.draw()
  3304. self.toggle_axis = True
  3305. else:
  3306. if self.is_legacy is False:
  3307. self.plotcanvas.v_line.parent = None
  3308. self.plotcanvas.h_line.parent = None
  3309. else:
  3310. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3311. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3312. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3313. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3314. self.plotcanvas.canvas.draw()
  3315. self.toggle_axis = False
  3316. def on_toggle_hud(self):
  3317. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3318. def on_toggle_grid_lines(self):
  3319. self.defaults.report_usage("on_toggle_grd_lines()")
  3320. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3321. if tt_settings.contains("theme"):
  3322. theme = tt_settings.value('theme', type=str)
  3323. else:
  3324. theme = 'white'
  3325. if self.toggle_grid_lines is False:
  3326. if self.is_legacy is False:
  3327. if theme == 'white':
  3328. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3329. else:
  3330. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3331. else:
  3332. self.plotcanvas.axes.grid(True)
  3333. try:
  3334. self.plotcanvas.canvas.draw()
  3335. except IndexError:
  3336. pass
  3337. pass
  3338. self.toggle_grid_lines = True
  3339. else:
  3340. if self.is_legacy is False:
  3341. if theme == 'white':
  3342. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3343. else:
  3344. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3345. else:
  3346. self.plotcanvas.axes.grid(False)
  3347. try:
  3348. self.plotcanvas.canvas.draw()
  3349. except IndexError:
  3350. pass
  3351. self.toggle_grid_lines = False
  3352. if self.is_legacy is False:
  3353. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3354. # - perhaps is a bug in VisPy implementation
  3355. if self.grid_status():
  3356. self.app_cursor.enabled = False
  3357. self.app_cursor.enabled = True
  3358. else:
  3359. self.app_cursor.enabled = True
  3360. self.app_cursor.enabled = False
  3361. def on_update_exc_export(self, state):
  3362. """
  3363. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3364. if the update_excellon_cb checkbox is checked
  3365. :param state: state of the checkbox whose signals is tied to his slot
  3366. :return:
  3367. """
  3368. if state:
  3369. # first try to disconnect
  3370. try:
  3371. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3372. disconnect(self.on_excellon_format_changed)
  3373. except TypeError:
  3374. pass
  3375. try:
  3376. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3377. disconnect(self.on_excellon_format_changed)
  3378. except TypeError:
  3379. pass
  3380. try:
  3381. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3382. disconnect(self.on_excellon_format_changed)
  3383. except TypeError:
  3384. pass
  3385. try:
  3386. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3387. disconnect(self.on_excellon_format_changed)
  3388. except TypeError:
  3389. pass
  3390. try:
  3391. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3392. disconnect(self.on_excellon_zeros_changed)
  3393. except TypeError:
  3394. pass
  3395. try:
  3396. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3397. disconnect(self.on_excellon_zeros_changed)
  3398. except TypeError:
  3399. pass
  3400. # the connect them
  3401. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3402. self.on_excellon_format_changed)
  3403. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3404. self.on_excellon_format_changed)
  3405. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3406. self.on_excellon_format_changed)
  3407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3408. self.on_excellon_format_changed)
  3409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3410. self.on_excellon_zeros_changed)
  3411. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3412. self.on_excellon_units_changed)
  3413. else:
  3414. # disconnect the signals
  3415. try:
  3416. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3417. disconnect(self.on_excellon_format_changed)
  3418. except TypeError:
  3419. pass
  3420. try:
  3421. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3422. disconnect(self.on_excellon_format_changed)
  3423. except TypeError:
  3424. pass
  3425. try:
  3426. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3427. disconnect(self.on_excellon_format_changed)
  3428. except TypeError:
  3429. pass
  3430. try:
  3431. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3432. disconnect(self.on_excellon_format_changed)
  3433. except TypeError:
  3434. pass
  3435. try:
  3436. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3437. disconnect(self.on_excellon_zeros_changed)
  3438. except TypeError:
  3439. pass
  3440. try:
  3441. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3442. disconnect(self.on_excellon_zeros_changed)
  3443. except TypeError:
  3444. pass
  3445. def on_excellon_format_changed(self):
  3446. """
  3447. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3448. :return: None
  3449. """
  3450. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3451. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3452. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3453. )
  3454. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3455. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3456. )
  3457. else:
  3458. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3459. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3460. )
  3461. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3462. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3463. )
  3464. def on_excellon_zeros_changed(self):
  3465. """
  3466. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3467. :return: None
  3468. """
  3469. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3470. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3471. )
  3472. def on_excellon_units_changed(self):
  3473. """
  3474. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3475. :return: None
  3476. """
  3477. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3478. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3479. )
  3480. self.on_excellon_format_changed()
  3481. def on_film_color_entry(self):
  3482. self.defaults['tools_film_color'] = \
  3483. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3484. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3485. "background-color:%s;"
  3486. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3487. )
  3488. def on_film_color_button(self):
  3489. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3490. c_dialog = QtWidgets.QColorDialog()
  3491. film_color = c_dialog.getColor(initial=current_color)
  3492. if film_color.isValid() is False:
  3493. return
  3494. # if new color is different then mark that the Preferences are changed
  3495. if film_color != current_color:
  3496. self.preferencesUiManager.on_preferences_edited()
  3497. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3498. "background-color:%s;"
  3499. "border-color: dimgray" % str(film_color.name())
  3500. )
  3501. new_val_sel = str(film_color.name())
  3502. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3503. self.defaults['tools_film_color'] = new_val_sel
  3504. def on_qrcode_fill_color_entry(self):
  3505. self.defaults['tools_qrcode_fill_color'] = \
  3506. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3507. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3508. "background-color:%s;"
  3509. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3510. )
  3511. def on_qrcode_fill_color_button(self):
  3512. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3513. c_dialog = QtWidgets.QColorDialog()
  3514. fill_color = c_dialog.getColor(initial=current_color)
  3515. if fill_color.isValid() is False:
  3516. return
  3517. # if new color is different then mark that the Preferences are changed
  3518. if fill_color != current_color:
  3519. self.preferencesUiManager.on_preferences_edited()
  3520. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3521. "background-color:%s;"
  3522. "border-color: dimgray" % str(fill_color.name())
  3523. )
  3524. new_val_sel = str(fill_color.name())
  3525. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3526. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3527. def on_qrcode_back_color_entry(self):
  3528. self.defaults['tools_qrcode_back_color'] = \
  3529. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3530. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3531. "background-color:%s;"
  3532. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3533. )
  3534. def on_qrcode_back_color_button(self):
  3535. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3536. c_dialog = QtWidgets.QColorDialog()
  3537. back_color = c_dialog.getColor(initial=current_color)
  3538. if back_color.isValid() is False:
  3539. return
  3540. # if new color is different then mark that the Preferences are changed
  3541. if back_color != current_color:
  3542. self.preferencesUiManager.on_preferences_edited()
  3543. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3544. "background-color:%s;"
  3545. "border-color: dimgray" % str(back_color.name())
  3546. )
  3547. new_val_sel = str(back_color.name())
  3548. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3549. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3550. def on_tab_rmb_click(self, checked):
  3551. self.ui.notebook.set_detachable(val=checked)
  3552. self.defaults["global_tabs_detachable"] = checked
  3553. self.ui.plot_tab_area.set_detachable(val=checked)
  3554. self.defaults["global_tabs_detachable"] = checked
  3555. def on_tab_setup_context_menu(self):
  3556. initial_checked = self.defaults["global_tabs_detachable"]
  3557. action_name = str(_("Detachable Tabs"))
  3558. action = QtWidgets.QAction(self)
  3559. action.setCheckable(True)
  3560. action.setText(action_name)
  3561. action.setChecked(initial_checked)
  3562. self.ui.notebook.tabBar.addAction(action)
  3563. self.ui.plot_tab_area.tabBar.addAction(action)
  3564. try:
  3565. action.triggered.disconnect()
  3566. except TypeError:
  3567. pass
  3568. action.triggered.connect(self.on_tab_rmb_click)
  3569. def on_deselect_all(self):
  3570. self.collection.set_all_inactive()
  3571. self.delete_selection_shape()
  3572. def on_workspace_modified(self):
  3573. # self.save_defaults(silent=True)
  3574. self.plotcanvas.delete_workspace()
  3575. self.preferencesUiManager.defaults_read_form()
  3576. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3577. def on_workspace(self):
  3578. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3579. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3580. self.inform.emit(_("Workspace enabled."))
  3581. else:
  3582. self.plotcanvas.delete_workspace()
  3583. self.inform.emit(_("Workspace disabled."))
  3584. self.preferencesUiManager.defaults_read_form()
  3585. # self.save_defaults(silent=True)
  3586. def on_workspace_toggle(self):
  3587. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3588. try:
  3589. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3590. except TypeError:
  3591. pass
  3592. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3593. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3594. self.on_workspace()
  3595. def on_cursor_type(self, val):
  3596. """
  3597. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3598. :return: None
  3599. """
  3600. self.app_cursor.enabled = False
  3601. if val == 'small':
  3602. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3603. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3604. self.app_cursor = self.plotcanvas.new_cursor()
  3605. else:
  3606. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3607. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3608. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3609. if self.ui.grid_snap_btn.isChecked():
  3610. self.app_cursor.enabled = True
  3611. else:
  3612. self.app_cursor.enabled = False
  3613. def on_tool_add_keypress(self):
  3614. # ## Current application units in Upper Case
  3615. self.units = self.defaults['units'].upper()
  3616. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3617. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3618. if notebook_widget_name == 'selected_tab':
  3619. if self.collection.get_active().kind == 'geometry':
  3620. # Tool add works for Geometry only if Advanced is True in Preferences
  3621. if self.defaults["global_app_level"] == 'a':
  3622. tool_add_popup = FCInputDialog(title="New Tool ...",
  3623. text='Enter a Tool Diameter:',
  3624. min=0.0000, max=99.9999, decimals=4)
  3625. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3626. val, ok = tool_add_popup.get_value()
  3627. if ok:
  3628. if float(val) == 0:
  3629. self.inform.emit('[WARNING_NOTCL] %s' %
  3630. _("Please enter a tool diameter with non-zero value, in Float format."))
  3631. return
  3632. self.collection.get_active().on_tool_add(dia=float(val))
  3633. else:
  3634. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3635. else:
  3636. msgbox = QtWidgets.QMessageBox()
  3637. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3638. "Go to Preferences -> General - Show Advanced Options."))
  3639. msgbox.setWindowTitle("Tool adding ...")
  3640. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3641. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3642. msgbox.setDefaultButton(bt_ok)
  3643. msgbox.exec_()
  3644. # work only if the notebook tab on focus is the Tools_Tab
  3645. if notebook_widget_name == 'tool_tab':
  3646. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3647. # and only if the tool is NCC Tool
  3648. if tool_widget == self.ncclear_tool.toolName:
  3649. self.ncclear_tool.on_add_tool_by_key()
  3650. # and only if the tool is Paint Area Tool
  3651. elif tool_widget == self.paint_tool.toolName:
  3652. self.paint_tool.on_add_tool_by_key()
  3653. # and only if the tool is Solder Paste Dispensing Tool
  3654. elif tool_widget == self.paste_tool.toolName:
  3655. self.paste_tool.on_add_tool_by_key()
  3656. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3657. # See description below.
  3658. def on_delete_keypress(self):
  3659. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3660. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3661. if notebook_widget_name == 'selected_tab':
  3662. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3663. self.collection.get_active().on_tool_delete()
  3664. # work only if the notebook tab on focus is the Tools_Tab
  3665. elif notebook_widget_name == 'tool_tab':
  3666. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3667. # and only if the tool is NCC Tool
  3668. if tool_widget == self.ncclear_tool.toolName:
  3669. self.ncclear_tool.on_tool_delete()
  3670. # and only if the tool is Paint Tool
  3671. elif tool_widget == self.paint_tool.toolName:
  3672. self.paint_tool.on_tool_delete()
  3673. # and only if the tool is Solder Paste Dispensing Tool
  3674. elif tool_widget == self.paste_tool.toolName:
  3675. self.paste_tool.on_tool_delete()
  3676. else:
  3677. self.on_delete()
  3678. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3679. # some screens you have to be careful where you hover with your mouse.
  3680. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3681. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3682. # Complicated, I know :)
  3683. def on_delete(self, force_deletion=False):
  3684. """
  3685. Delete the currently selected FlatCAMObjs.
  3686. :param force_deletion: used by Tcl command
  3687. :return: None
  3688. """
  3689. self.defaults.report_usage("on_delete()")
  3690. response = None
  3691. bt_ok = None
  3692. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3693. # a geometry object before we update it.
  3694. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3695. and self.grb_editor.editor_active is False:
  3696. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3697. msgbox = QtWidgets.QMessageBox()
  3698. msgbox.setWindowTitle(_("Delete objects"))
  3699. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3700. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3701. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3702. "the selected objects?"))
  3703. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3704. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3705. msgbox.setDefaultButton(bt_ok)
  3706. msgbox.exec_()
  3707. response = msgbox.clickedButton()
  3708. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3709. response = bt_ok
  3710. if response == bt_ok:
  3711. if self.collection.get_active():
  3712. self.log.debug("App.on_delete()")
  3713. for obj_active in self.collection.get_selected():
  3714. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3715. if obj_active.kind == 'gerber':
  3716. for el in obj_active.mark_shapes:
  3717. obj_active.mark_shapes[el].clear(update=True)
  3718. obj_active.mark_shapes[el].enabled = False
  3719. # obj_active.mark_shapes[el] = None
  3720. del el
  3721. elif isinstance(obj_active, CNCJobObject):
  3722. try:
  3723. obj_active.text_col.enabled = False
  3724. del obj_active.text_col
  3725. obj_active.annotation.clear(update=True)
  3726. del obj_active.annotation
  3727. except AttributeError as e:
  3728. log.debug(
  3729. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3730. )
  3731. while self.collection.get_selected():
  3732. self.delete_first_selected()
  3733. self.inform.emit('%s...' % _("Object(s) deleted"))
  3734. # make sure that the selection shape is deleted, too
  3735. self.delete_selection_shape()
  3736. # if there are no longer objects delete also the exclusion areas shapes
  3737. if not self.collection.get_list():
  3738. self.exc_areas.clear_shapes()
  3739. else:
  3740. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3741. else:
  3742. self.inform.emit(_("Save the work in Editor and try again ..."))
  3743. def delete_first_selected(self):
  3744. # Keep this for later
  3745. try:
  3746. sel_obj = self.collection.get_active()
  3747. name = sel_obj.options["name"]
  3748. isPlotted = sel_obj.options["plot"]
  3749. except AttributeError:
  3750. self.log.debug("Nothing selected for deletion")
  3751. return
  3752. if self.is_legacy is True:
  3753. # Remove plot only if the object was plotted otherwise delaxes will fail
  3754. if isPlotted:
  3755. try:
  3756. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3757. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3758. except Exception as e:
  3759. log.debug("App.delete_first_selected() --> %s" % str(e))
  3760. self.plotcanvas.auto_adjust_axes()
  3761. # Remove from dictionary
  3762. self.collection.delete_active()
  3763. # Clear form
  3764. self.setup_component_editor()
  3765. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3766. def on_set_origin(self):
  3767. """
  3768. Set the origin to the left mouse click position
  3769. :return: None
  3770. """
  3771. # display the message for the user
  3772. # and ask him to click on the desired position
  3773. self.defaults.report_usage("on_set_origin()")
  3774. def origin_replot():
  3775. def worker_task():
  3776. with self.proc_container.new('%s...' % _("Plotting")):
  3777. for obj in self.collection.get_list():
  3778. obj.plot()
  3779. self.plotcanvas.fit_view()
  3780. if self.is_legacy:
  3781. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3782. else:
  3783. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3784. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3785. self.inform.emit(_('Click to set the origin ...'))
  3786. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3787. # first disconnect it as it may have been used by something else
  3788. try:
  3789. self.replot_signal.disconnect()
  3790. except TypeError:
  3791. pass
  3792. self.replot_signal[list].connect(origin_replot)
  3793. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3794. """
  3795. :param event:
  3796. :param location:
  3797. :param noplot:
  3798. :param use_thread:
  3799. :return:
  3800. """
  3801. noplot_sig = noplot
  3802. def worker_task():
  3803. with self.proc_container.new(_("Setting Origin...")):
  3804. obj_list = self.collection.get_list()
  3805. for obj in obj_list:
  3806. obj.offset((x, y))
  3807. self.app_obj.object_changed.emit(obj)
  3808. # Update the object bounding box options
  3809. a, b, c, d = obj.bounds()
  3810. obj.options['xmin'] = a
  3811. obj.options['ymin'] = b
  3812. obj.options['xmax'] = c
  3813. obj.options['ymax'] = d
  3814. self.inform.emit('[success] %s...' % _('Origin set'))
  3815. for obj in obj_list:
  3816. out_name = obj.options["name"]
  3817. if obj.kind == 'gerber':
  3818. obj.source_file = self.export_gerber(
  3819. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3820. elif obj.kind == 'excellon':
  3821. obj.source_file = self.export_excellon(
  3822. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3823. if noplot_sig is False:
  3824. self.replot_signal.emit([])
  3825. if location is not None:
  3826. if len(location) != 2:
  3827. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3828. return 'fail'
  3829. x, y = location
  3830. if use_thread is True:
  3831. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3832. else:
  3833. worker_task()
  3834. self.should_we_save = True
  3835. return
  3836. if event is not None and event.button == 1:
  3837. if self.is_legacy is False:
  3838. event_pos = event.pos
  3839. else:
  3840. event_pos = (event.xdata, event.ydata)
  3841. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3842. if self.grid_status():
  3843. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3844. else:
  3845. pos = pos_canvas
  3846. x = 0 - pos[0]
  3847. y = 0 - pos[1]
  3848. if use_thread is True:
  3849. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3850. else:
  3851. worker_task()
  3852. self.should_we_save = True
  3853. def on_move2origin(self, use_thread=True):
  3854. """
  3855. Move selected objects to origin.
  3856. :param use_thread: Control if to use threaded operation. Boolean.
  3857. :return:
  3858. """
  3859. def worker_task():
  3860. with self.proc_container.new(_("Moving to Origin...")):
  3861. obj_list = self.collection.get_selected()
  3862. if not obj_list:
  3863. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3864. return
  3865. xminlist = []
  3866. yminlist = []
  3867. # first get a bounding box to fit all
  3868. for obj in obj_list:
  3869. xmin, ymin, xmax, ymax = obj.bounds()
  3870. xminlist.append(xmin)
  3871. yminlist.append(ymin)
  3872. # get the minimum x,y for all objects selected
  3873. x = min(xminlist)
  3874. y = min(yminlist)
  3875. for obj in obj_list:
  3876. obj.offset((-x, -y))
  3877. self.app_obj.object_changed.emit(obj)
  3878. # Update the object bounding box options
  3879. a, b, c, d = obj.bounds()
  3880. obj.options['xmin'] = a
  3881. obj.options['ymin'] = b
  3882. obj.options['xmax'] = c
  3883. obj.options['ymax'] = d
  3884. for obj in obj_list:
  3885. obj.plot()
  3886. for obj in obj_list:
  3887. out_name = obj.options["name"]
  3888. if obj.kind == 'gerber':
  3889. obj.source_file = self.export_gerber(
  3890. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3891. elif obj.kind == 'excellon':
  3892. obj.source_file = self.export_excellon(
  3893. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3894. self.inform.emit('[success] %s...' % _('Origin set'))
  3895. if use_thread is True:
  3896. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3897. else:
  3898. worker_task()
  3899. self.should_we_save = True
  3900. def on_jump_to(self, custom_location=None, fit_center=True):
  3901. """
  3902. Jump to a location by setting the mouse cursor location.
  3903. :param custom_location: Jump to a specified point. (x, y) tuple.
  3904. :param fit_center: If to fit view. Boolean.
  3905. :return:
  3906. """
  3907. self.defaults.report_usage("on_jump_to()")
  3908. if not custom_location:
  3909. dia_box_location = None
  3910. try:
  3911. dia_box_location = eval(self.clipboard.text())
  3912. except Exception:
  3913. pass
  3914. if type(dia_box_location) == tuple:
  3915. dia_box_location = str(dia_box_location)
  3916. else:
  3917. dia_box_location = None
  3918. # dia_box = Dialog_box(title=_("Jump to ..."),
  3919. # label=_("Enter the coordinates in format X,Y:"),
  3920. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3921. # initial_text=dia_box_location)
  3922. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3923. label=_("Enter the coordinates in format X,Y:"),
  3924. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3925. initial_text=dia_box_location,
  3926. reference=self.defaults['global_jump_ref'])
  3927. if dia_box.ok is True:
  3928. try:
  3929. location = eval(dia_box.location)
  3930. if not isinstance(location, tuple):
  3931. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3932. return
  3933. if dia_box.reference == 'rel':
  3934. rel_x = self.mouse[0] + location[0]
  3935. rel_y = self.mouse[1] + location[1]
  3936. location = (rel_x, rel_y)
  3937. self.defaults['global_jump_ref'] = dia_box.reference
  3938. except Exception:
  3939. return
  3940. else:
  3941. return
  3942. else:
  3943. location = custom_location
  3944. self.jump_signal.emit(location)
  3945. if fit_center:
  3946. self.plotcanvas.fit_center(loc=location)
  3947. cursor = QtGui.QCursor()
  3948. if self.is_legacy is False:
  3949. # I don't know where those differences come from but they are constant for the current
  3950. # execution of the application and they are multiples of a value around 0.0263mm.
  3951. # In a random way sometimes they are more sometimes they are less
  3952. # if units == 'MM':
  3953. # cal_factor = 0.0263
  3954. # else:
  3955. # cal_factor = 0.0263 / 25.4
  3956. cal_location = (location[0], location[1])
  3957. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3958. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3959. j_pos = (
  3960. int(canvas_origin.x() + round(jump_loc[0])),
  3961. int(canvas_origin.y() + round(jump_loc[1]))
  3962. )
  3963. cursor.setPos(j_pos[0], j_pos[1])
  3964. else:
  3965. # find the canvas origin which is in the top left corner
  3966. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3967. # determine the coordinates for the lowest left point of the canvas
  3968. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3969. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3970. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3971. # canvas) and the point (width, height) is in the top-right location
  3972. loc = self.plotcanvas.axes.transData.transform_point(location)
  3973. j_pos = (
  3974. int(x0 + loc[0]),
  3975. int(y0 - loc[1])
  3976. )
  3977. cursor.setPos(j_pos[0], j_pos[1])
  3978. self.plotcanvas.mouse = [location[0], location[1]]
  3979. if self.defaults["global_cursor_color_enabled"] is True:
  3980. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3981. else:
  3982. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3983. if self.grid_status():
  3984. # Update cursor
  3985. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3986. symbol='++', edge_color=self.cursor_color_3D,
  3987. edge_width=self.defaults["global_cursor_width"],
  3988. size=self.defaults["global_cursor_size"])
  3989. # Set the relative position label
  3990. dx = location[0] - float(self.rel_point1[0])
  3991. dy = location[1] - float(self.rel_point1[1])
  3992. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3993. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3994. # # Set the position label
  3995. #
  3996. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3997. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3998. units = self.defaults["units"].lower()
  3999. self.plotcanvas.text_hud.text = \
  4000. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4001. dx, units, dy, units, location[0], units, location[1], units)
  4002. self.inform.emit('[success] %s' % _("Done."))
  4003. return location
  4004. def on_locate(self, obj, fit_center=True):
  4005. """
  4006. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4007. :param obj: The object on which to locate certain points
  4008. :param fit_center: If to fit view. Boolean.
  4009. :return: A point location. (x, y) tuple.
  4010. """
  4011. self.defaults.report_usage("on_locate()")
  4012. if obj is None:
  4013. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4014. return 'fail'
  4015. class DialogBoxChoice(QtWidgets.QDialog):
  4016. def __init__(self, title=None, icon=None, choice='bl'):
  4017. """
  4018. :param title: string with the window title
  4019. """
  4020. super(DialogBoxChoice, self).__init__()
  4021. self.ok = False
  4022. self.setWindowIcon(icon)
  4023. self.setWindowTitle(str(title))
  4024. self.form = QtWidgets.QFormLayout(self)
  4025. self.ref_radio = RadioSet([
  4026. {"label": _("Bottom-Left"), "value": "bl"},
  4027. {"label": _("Top-Left"), "value": "tl"},
  4028. {"label": _("Bottom-Right"), "value": "br"},
  4029. {"label": _("Top-Right"), "value": "tr"},
  4030. {"label": _("Center"), "value": "c"}
  4031. ], orientation='vertical', stretch=False)
  4032. self.ref_radio.set_value(choice)
  4033. self.form.addRow(self.ref_radio)
  4034. self.button_box = QtWidgets.QDialogButtonBox(
  4035. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4036. Qt.Horizontal, parent=self)
  4037. self.form.addRow(self.button_box)
  4038. self.button_box.accepted.connect(self.accept)
  4039. self.button_box.rejected.connect(self.reject)
  4040. if self.exec_() == QtWidgets.QDialog.Accepted:
  4041. self.ok = True
  4042. self.location_point = self.ref_radio.get_value()
  4043. else:
  4044. self.ok = False
  4045. self.location_point = None
  4046. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4047. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4048. choice=self.defaults['global_locate_pt'])
  4049. if dia_box.ok is True:
  4050. try:
  4051. location_point = dia_box.location_point
  4052. self.defaults['global_locate_pt'] = dia_box.location_point
  4053. except Exception:
  4054. return
  4055. else:
  4056. return
  4057. loc_b = obj.bounds()
  4058. if location_point == 'bl':
  4059. location = (loc_b[0], loc_b[1])
  4060. elif location_point == 'tl':
  4061. location = (loc_b[0], loc_b[3])
  4062. elif location_point == 'br':
  4063. location = (loc_b[2], loc_b[1])
  4064. elif location_point == 'tr':
  4065. location = (loc_b[2], loc_b[3])
  4066. else:
  4067. # center
  4068. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4069. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4070. location = (cx, cy)
  4071. self.locate_signal.emit(location, location_point)
  4072. if fit_center:
  4073. self.plotcanvas.fit_center(loc=location)
  4074. cursor = QtGui.QCursor()
  4075. if self.is_legacy is False:
  4076. # I don't know where those differences come from but they are constant for the current
  4077. # execution of the application and they are multiples of a value around 0.0263mm.
  4078. # In a random way sometimes they are more sometimes they are less
  4079. # if units == 'MM':
  4080. # cal_factor = 0.0263
  4081. # else:
  4082. # cal_factor = 0.0263 / 25.4
  4083. cal_location = (location[0], location[1])
  4084. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4085. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4086. j_pos = (
  4087. int(canvas_origin.x() + round(jump_loc[0])),
  4088. int(canvas_origin.y() + round(jump_loc[1]))
  4089. )
  4090. cursor.setPos(j_pos[0], j_pos[1])
  4091. else:
  4092. # find the canvas origin which is in the top left corner
  4093. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4094. # determine the coordinates for the lowest left point of the canvas
  4095. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4096. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4097. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4098. # canvas) and the point (width, height) is in the top-right location
  4099. loc = self.plotcanvas.axes.transData.transform_point(location)
  4100. j_pos = (
  4101. int(x0 + loc[0]),
  4102. int(y0 - loc[1])
  4103. )
  4104. cursor.setPos(j_pos[0], j_pos[1])
  4105. self.plotcanvas.mouse = [location[0], location[1]]
  4106. if self.defaults["global_cursor_color_enabled"] is True:
  4107. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4108. else:
  4109. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4110. if self.grid_status():
  4111. # Update cursor
  4112. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4113. symbol='++', edge_color=self.cursor_color_3D,
  4114. edge_width=self.defaults["global_cursor_width"],
  4115. size=self.defaults["global_cursor_size"])
  4116. # Set the relative position label
  4117. self.dx = location[0] - float(self.rel_point1[0])
  4118. self.dy = location[1] - float(self.rel_point1[1])
  4119. # Set the position label
  4120. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4121. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4122. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4123. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4124. units = self.defaults["units"].lower()
  4125. self.plotcanvas.text_hud.text = \
  4126. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4127. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4128. self.inform.emit('[success] %s' % _("Done."))
  4129. return location
  4130. def on_copy_command(self):
  4131. """
  4132. Will copy a selection of objects, creating new objects.
  4133. :return:
  4134. """
  4135. self.defaults.report_usage("on_copy_command()")
  4136. def initialize(obj_init, app):
  4137. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4138. try:
  4139. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4140. except AttributeError:
  4141. pass
  4142. try:
  4143. obj_init.apertures = deepcopy(obj.apertures)
  4144. except AttributeError:
  4145. pass
  4146. try:
  4147. if obj.tools:
  4148. obj_init.tools = deepcopy(obj.tools)
  4149. except Exception as err:
  4150. log.debug("App.on_copy_command() --> %s" % str(err))
  4151. try:
  4152. obj_init.source_file = deepcopy(obj.source_file)
  4153. except (AttributeError, TypeError):
  4154. pass
  4155. def initialize_excellon(obj_init, app):
  4156. obj_init.source_file = deepcopy(obj.source_file)
  4157. obj_init.tools = deepcopy(obj.tools)
  4158. # drills are offset, so they need to be deep copied
  4159. obj_init.drills = deepcopy(obj.drills)
  4160. # slots are offset, so they need to be deep copied
  4161. obj_init.slots = deepcopy(obj.slots)
  4162. obj_init.create_geometry()
  4163. def initialize_script(obj_init, app_obj):
  4164. obj_init.source_file = deepcopy(obj.source_file)
  4165. def initialize_document(obj_init, app_obj):
  4166. obj_init.source_file = deepcopy(obj.source_file)
  4167. for obj in self.collection.get_selected():
  4168. obj_name = obj.options["name"]
  4169. try:
  4170. if isinstance(obj, ExcellonObject):
  4171. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4172. elif isinstance(obj, GerberObject):
  4173. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4174. elif isinstance(obj, GeometryObject):
  4175. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4176. elif isinstance(obj, ScriptObject):
  4177. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4178. elif isinstance(obj, DocumentObject):
  4179. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4180. except Exception as e:
  4181. return "Operation failed: %s" % str(e)
  4182. def on_copy_object2(self, custom_name):
  4183. def initialize_geometry(obj_init, app):
  4184. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4185. try:
  4186. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4187. except AttributeError:
  4188. pass
  4189. try:
  4190. obj_init.apertures = deepcopy(obj.apertures)
  4191. except AttributeError:
  4192. pass
  4193. try:
  4194. if obj.tools:
  4195. obj_init.tools = deepcopy(obj.tools)
  4196. except Exception as ee:
  4197. log.debug("on_copy_object2() --> %s" % str(ee))
  4198. def initialize_gerber(obj_init, app):
  4199. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4200. obj_init.apertures = deepcopy(obj.apertures)
  4201. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4202. def initialize_excellon(obj_init, app):
  4203. obj_init.tools = deepcopy(obj.tools)
  4204. # drills are offset, so they need to be deep copied
  4205. obj_init.drills = deepcopy(obj.drills)
  4206. # slots are offset, so they need to be deep copied
  4207. obj_init.slots = deepcopy(obj.slots)
  4208. obj_init.create_geometry()
  4209. for obj in self.collection.get_selected():
  4210. obj_name = obj.options["name"]
  4211. try:
  4212. if isinstance(obj, ExcellonObject):
  4213. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4214. elif isinstance(obj, GerberObject):
  4215. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4216. elif isinstance(obj, GeometryObject):
  4217. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4218. except Exception as er:
  4219. return "Operation failed: %s" % str(er)
  4220. def on_rename_object(self, text):
  4221. """
  4222. Will rename an object.
  4223. :param text: New name for the object.
  4224. :return:
  4225. """
  4226. self.defaults.report_usage("on_rename_object()")
  4227. named_obj = self.collection.get_active()
  4228. for obj in named_obj:
  4229. if obj is list:
  4230. self.on_rename_object(text)
  4231. else:
  4232. try:
  4233. obj.options['name'] = text
  4234. except Exception as e:
  4235. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4236. def convert_any2geo(self):
  4237. """
  4238. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4239. :return:
  4240. """
  4241. self.defaults.report_usage("convert_any2geo()")
  4242. def initialize(obj_init, app):
  4243. obj_init.solid_geometry = obj.solid_geometry
  4244. try:
  4245. obj_init.follow_geometry = obj.follow_geometry
  4246. except AttributeError:
  4247. pass
  4248. try:
  4249. obj_init.apertures = obj.apertures
  4250. except AttributeError:
  4251. pass
  4252. try:
  4253. if obj.tools:
  4254. obj_init.tools = obj.tools
  4255. except AttributeError:
  4256. pass
  4257. def initialize_excellon(obj_init, app):
  4258. # objs = self.collection.get_selected()
  4259. # GeometryObject.merge(objs, obj)
  4260. solid_geo = []
  4261. for tool in obj.tools:
  4262. for geo in obj.tools[tool]['solid_geometry']:
  4263. solid_geo.append(geo)
  4264. obj_init.solid_geometry = deepcopy(solid_geo)
  4265. if not self.collection.get_selected():
  4266. log.warning("App.convert_any2geo --> No object selected")
  4267. self.inform.emit('[WARNING_NOTCL] %s' %
  4268. _("No object is selected. Select an object and try again."))
  4269. return
  4270. for obj in self.collection.get_selected():
  4271. obj_name = obj.options["name"]
  4272. try:
  4273. if isinstance(obj, ExcellonObject):
  4274. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4275. else:
  4276. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4277. except Exception as e:
  4278. return "Operation failed: %s" % str(e)
  4279. def convert_any2gerber(self):
  4280. """
  4281. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4282. :return:
  4283. """
  4284. self.defaults.report_usage("convert_any2gerber()")
  4285. def initialize_geometry(obj_init, app):
  4286. apertures = {}
  4287. apid = 0
  4288. apertures[str(apid)] = {}
  4289. apertures[str(apid)]['geometry'] = []
  4290. for obj_orig in obj.solid_geometry:
  4291. new_elem = {}
  4292. new_elem['solid'] = obj_orig
  4293. try:
  4294. new_elem['follow'] = obj_orig.exterior
  4295. except AttributeError:
  4296. pass
  4297. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4298. apertures[str(apid)]['size'] = 0.0
  4299. apertures[str(apid)]['type'] = 'C'
  4300. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4301. obj_init.apertures = deepcopy(apertures)
  4302. def initialize_excellon(obj_init, app):
  4303. apertures = {}
  4304. apid = 10
  4305. for tool in obj.tools:
  4306. apertures[str(apid)] = {}
  4307. apertures[str(apid)]['geometry'] = []
  4308. for geo in obj.tools[tool]['solid_geometry']:
  4309. new_el = {}
  4310. new_el['solid'] = geo
  4311. new_el['follow'] = geo.exterior
  4312. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4313. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4314. apertures[str(apid)]['type'] = 'C'
  4315. apid += 1
  4316. # create solid_geometry
  4317. solid_geometry = []
  4318. for apid in apertures:
  4319. for geo_el in apertures[apid]['geometry']:
  4320. solid_geometry.append(geo_el['solid'])
  4321. solid_geometry = MultiPolygon(solid_geometry)
  4322. solid_geometry = solid_geometry.buffer(0.0000001)
  4323. obj_init.solid_geometry = deepcopy(solid_geometry)
  4324. obj_init.apertures = deepcopy(apertures)
  4325. # clear the working objects (perhaps not necessary due of Python GC)
  4326. apertures.clear()
  4327. if not self.collection.get_selected():
  4328. log.warning("App.convert_any2gerber --> No object selected")
  4329. self.inform.emit('[WARNING_NOTCL] %s' %
  4330. _("No object is selected. Select an object and try again."))
  4331. return
  4332. for obj in self.collection.get_selected():
  4333. obj_name = obj.options["name"]
  4334. try:
  4335. if isinstance(obj, ExcellonObject):
  4336. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4337. elif isinstance(obj, GeometryObject):
  4338. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4339. else:
  4340. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4341. except Exception as e:
  4342. return "Operation failed: %s" % str(e)
  4343. def abort_all_tasks(self):
  4344. """
  4345. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4346. on the first possible occasion.
  4347. :return:
  4348. """
  4349. if self.abort_flag is False:
  4350. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4351. self.abort_flag = True
  4352. self.cleanup.emit()
  4353. def app_is_idle(self):
  4354. if self.abort_flag:
  4355. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4356. self.abort_flag = False
  4357. def on_selectall(self):
  4358. """
  4359. Will draw a selection box shape around the selected objects.
  4360. :return:
  4361. """
  4362. self.defaults.report_usage("on_selectall()")
  4363. # delete the possible selection box around a possible selected object
  4364. self.delete_selection_shape()
  4365. for name in self.collection.get_names():
  4366. self.collection.set_active(name)
  4367. curr_sel_obj = self.collection.get_by_name(name)
  4368. # create the selection box around the selected object
  4369. if self.defaults['global_selection_shape'] is True:
  4370. self.draw_selection_shape(curr_sel_obj)
  4371. def on_preferences(self):
  4372. """
  4373. Adds the Preferences in a Tab in Plot Area
  4374. :return:
  4375. """
  4376. # add the tab if it was closed
  4377. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4378. # delete the absolute and relative position and messages in the infobar
  4379. self.ui.position_label.setText("")
  4380. # self.ui.rel_position_label.setText("")
  4381. # Switch plot_area to preferences page
  4382. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4383. # self.ui.show()
  4384. # detect changes in the preferences
  4385. for idx in range(self.ui.pref_tab_area.count()):
  4386. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4387. try:
  4388. try:
  4389. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4390. except (TypeError, AttributeError):
  4391. pass
  4392. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4393. except AttributeError:
  4394. pass
  4395. try:
  4396. try:
  4397. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4398. except (TypeError, AttributeError):
  4399. pass
  4400. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4401. except AttributeError:
  4402. pass
  4403. try:
  4404. try:
  4405. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4406. except (TypeError, AttributeError):
  4407. pass
  4408. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4409. except AttributeError:
  4410. pass
  4411. try:
  4412. try:
  4413. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4414. except (TypeError, AttributeError):
  4415. pass
  4416. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4417. except AttributeError:
  4418. pass
  4419. try:
  4420. try:
  4421. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4422. except (TypeError, AttributeError):
  4423. pass
  4424. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4425. except AttributeError:
  4426. pass
  4427. def on_tools_database(self, source='app'):
  4428. """
  4429. Adds the Tools Database in a Tab in Plot Area.
  4430. :return:
  4431. """
  4432. for idx in range(self.ui.plot_tab_area.count()):
  4433. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4434. # there can be only one instance of Tools Database at one time
  4435. return
  4436. if source == 'app':
  4437. self.tools_db_tab = ToolsDB2(
  4438. app=self,
  4439. parent=self.ui,
  4440. callback_on_edited=self.on_tools_db_edited,
  4441. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4442. )
  4443. elif source == 'ncc':
  4444. self.tools_db_tab = ToolsDB2(
  4445. app=self,
  4446. parent=self.ui,
  4447. callback_on_edited=self.on_tools_db_edited,
  4448. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4449. )
  4450. elif source == 'paint':
  4451. self.tools_db_tab = ToolsDB2(
  4452. app=self,
  4453. parent=self.ui,
  4454. callback_on_edited=self.on_tools_db_edited,
  4455. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4456. )
  4457. # add the tab if it was closed
  4458. try:
  4459. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4460. self.tools_db_tab.setObjectName("database_tab")
  4461. except Exception as e:
  4462. log.debug("App.on_tools_database() --> %s" % str(e))
  4463. return
  4464. # delete the absolute and relative position and messages in the infobar
  4465. self.ui.position_label.setText("")
  4466. # self.ui.rel_position_label.setText("")
  4467. # Switch plot_area to preferences page
  4468. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4469. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4470. self.tools_db_tab.ui_connect()
  4471. def on_tools_db_edited(self):
  4472. """
  4473. Executed whenever a tool is edited in Tools Database.
  4474. Will color the text of the Tools Database tab to Red color.
  4475. :return:
  4476. """
  4477. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4478. for idx in range(self.ui.plot_tab_area.count()):
  4479. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4480. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4481. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4482. self.tools_db_changed_flag = True
  4483. def on_geometry_tool_add_from_db_executed(self, tool):
  4484. """
  4485. Here add the tool from DB in the selected geometry object.
  4486. :return:
  4487. """
  4488. tool_from_db = deepcopy(tool)
  4489. obj = self.collection.get_active()
  4490. if isinstance(obj, GeometryObject):
  4491. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4492. # close the tab and delete it
  4493. for idx in range(self.ui.plot_tab_area.count()):
  4494. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4495. wdg = self.ui.plot_tab_area.widget(idx)
  4496. wdg.deleteLater()
  4497. self.ui.plot_tab_area.removeTab(idx)
  4498. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4499. else:
  4500. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4501. def on_plot_area_tab_closed(self, tab_obj_name):
  4502. """
  4503. Executed whenever a QTab is closed in the Plot Area.
  4504. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4505. :return:
  4506. """
  4507. if tab_obj_name == "preferences_tab":
  4508. self.preferencesUiManager.on_close_preferences_tab()
  4509. elif tab_obj_name == "database_tab":
  4510. # disconnect the signals from the table widget in tab
  4511. self.tools_db_tab.ui_disconnect()
  4512. if self.tools_db_changed_flag is True:
  4513. msgbox = QtWidgets.QMessageBox()
  4514. msgbox.setText(_("One or more Tools are edited.\n"
  4515. "Do you want to update the Tools Database?"))
  4516. msgbox.setWindowTitle(_("Save Tools Database"))
  4517. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4518. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4519. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4520. msgbox.setDefaultButton(bt_yes)
  4521. msgbox.exec_()
  4522. response = msgbox.clickedButton()
  4523. if response == bt_yes:
  4524. self.tools_db_tab.on_save_tools_db()
  4525. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4526. else:
  4527. self.tools_db_changed_flag = False
  4528. self.inform.emit('')
  4529. return
  4530. self.tools_db_tab.deleteLater()
  4531. elif tab_obj_name == "text_editor_tab":
  4532. self.toggle_codeeditor = False
  4533. elif tab_obj_name == "bookmarks_tab":
  4534. self.book_dialog_tab.rebuild_actions()
  4535. self.book_dialog_tab.deleteLater()
  4536. else:
  4537. return
  4538. # def on_plotarea_tab_closed(self, tab_idx):
  4539. # """
  4540. #
  4541. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4542. # :return:
  4543. # """
  4544. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4545. #
  4546. # if widget is not None:
  4547. # widget.deleteLater()
  4548. # self.ui.plot_tab_area.removeTab(tab_idx)
  4549. def on_flipy(self):
  4550. """
  4551. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4552. :return:
  4553. """
  4554. self.defaults.report_usage("on_flipy()")
  4555. obj_list = self.collection.get_selected()
  4556. xminlist = []
  4557. yminlist = []
  4558. xmaxlist = []
  4559. ymaxlist = []
  4560. if not obj_list:
  4561. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4562. else:
  4563. try:
  4564. # first get a bounding box to fit all
  4565. for obj in obj_list:
  4566. xmin, ymin, xmax, ymax = obj.bounds()
  4567. xminlist.append(xmin)
  4568. yminlist.append(ymin)
  4569. xmaxlist.append(xmax)
  4570. ymaxlist.append(ymax)
  4571. # get the minimum x,y and maximum x,y for all objects selected
  4572. xminimal = min(xminlist)
  4573. yminimal = min(yminlist)
  4574. xmaximal = max(xmaxlist)
  4575. ymaximal = max(ymaxlist)
  4576. px = 0.5 * (xminimal + xmaximal)
  4577. py = 0.5 * (yminimal + ymaximal)
  4578. # execute mirroring
  4579. for obj in obj_list:
  4580. obj.mirror('X', [px, py])
  4581. obj.plot()
  4582. self.app_obj.object_changed.emit(obj)
  4583. self.inform.emit('[success] %s' %
  4584. _("Flip on Y axis done."))
  4585. except Exception as e:
  4586. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4587. return
  4588. def on_flipx(self):
  4589. """
  4590. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4591. :return:
  4592. """
  4593. self.defaults.report_usage("on_flipx()")
  4594. obj_list = self.collection.get_selected()
  4595. xminlist = []
  4596. yminlist = []
  4597. xmaxlist = []
  4598. ymaxlist = []
  4599. if not obj_list:
  4600. self.inform.emit('[WARNING_NOTCL] %s' %
  4601. _("No object selected to Flip on X axis."))
  4602. else:
  4603. try:
  4604. # first get a bounding box to fit all
  4605. for obj in obj_list:
  4606. xmin, ymin, xmax, ymax = obj.bounds()
  4607. xminlist.append(xmin)
  4608. yminlist.append(ymin)
  4609. xmaxlist.append(xmax)
  4610. ymaxlist.append(ymax)
  4611. # get the minimum x,y and maximum x,y for all objects selected
  4612. xminimal = min(xminlist)
  4613. yminimal = min(yminlist)
  4614. xmaximal = max(xmaxlist)
  4615. ymaximal = max(ymaxlist)
  4616. px = 0.5 * (xminimal + xmaximal)
  4617. py = 0.5 * (yminimal + ymaximal)
  4618. # execute mirroring
  4619. for obj in obj_list:
  4620. obj.mirror('Y', [px, py])
  4621. obj.plot()
  4622. self.app_obj.object_changed.emit(obj)
  4623. self.inform.emit('[success] %s' %
  4624. _("Flip on X axis done."))
  4625. except Exception as e:
  4626. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4627. return
  4628. def on_rotate(self, silent=False, preset=None):
  4629. """
  4630. Executed when Options -> Rotate Selection menu entry is clicked.
  4631. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4632. :param preset: A value to be used as predefined angle for rotation.
  4633. :return:
  4634. """
  4635. self.defaults.report_usage("on_rotate()")
  4636. obj_list = self.collection.get_selected()
  4637. xminlist = []
  4638. yminlist = []
  4639. xmaxlist = []
  4640. ymaxlist = []
  4641. if not obj_list:
  4642. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4643. else:
  4644. if silent is False:
  4645. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4646. min=-360, max=360, decimals=4,
  4647. init_val=float(self.defaults['tools_transform_rotate']))
  4648. num, ok = rotatebox.get_value()
  4649. else:
  4650. num = preset
  4651. ok = True
  4652. if ok:
  4653. try:
  4654. # first get a bounding box to fit all
  4655. for obj in obj_list:
  4656. xmin, ymin, xmax, ymax = obj.bounds()
  4657. xminlist.append(xmin)
  4658. yminlist.append(ymin)
  4659. xmaxlist.append(xmax)
  4660. ymaxlist.append(ymax)
  4661. # get the minimum x,y and maximum x,y for all objects selected
  4662. xminimal = min(xminlist)
  4663. yminimal = min(yminlist)
  4664. xmaximal = max(xmaxlist)
  4665. ymaximal = max(ymaxlist)
  4666. px = 0.5 * (xminimal + xmaximal)
  4667. py = 0.5 * (yminimal + ymaximal)
  4668. for sel_obj in obj_list:
  4669. sel_obj.rotate(-float(num), point=(px, py))
  4670. sel_obj.plot()
  4671. self.app_obj.object_changed.emit(sel_obj)
  4672. self.inform.emit('[success] %s' % _("Rotation done."))
  4673. except Exception as e:
  4674. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4675. return
  4676. def on_skewx(self):
  4677. """
  4678. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4679. :return:
  4680. """
  4681. self.defaults.report_usage("on_skewx()")
  4682. obj_list = self.collection.get_selected()
  4683. xminlist = []
  4684. yminlist = []
  4685. if not obj_list:
  4686. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4687. else:
  4688. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4689. min=-360, max=360, decimals=4,
  4690. init_val=float(self.defaults['tools_transform_skew_x']))
  4691. num, ok = skewxbox.get_value()
  4692. if ok:
  4693. # first get a bounding box to fit all
  4694. for obj in obj_list:
  4695. xmin, ymin, xmax, ymax = obj.bounds()
  4696. xminlist.append(xmin)
  4697. yminlist.append(ymin)
  4698. # get the minimum x,y and maximum x,y for all objects selected
  4699. xminimal = min(xminlist)
  4700. yminimal = min(yminlist)
  4701. for obj in obj_list:
  4702. obj.skew(num, 0, point=(xminimal, yminimal))
  4703. obj.plot()
  4704. self.app_obj.object_changed.emit(obj)
  4705. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4706. def on_skewy(self):
  4707. """
  4708. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4709. :return:
  4710. """
  4711. self.defaults.report_usage("on_skewy()")
  4712. obj_list = self.collection.get_selected()
  4713. xminlist = []
  4714. yminlist = []
  4715. if not obj_list:
  4716. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4717. else:
  4718. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4719. min=-360, max=360, decimals=4,
  4720. init_val=float(self.defaults['tools_transform_skew_y']))
  4721. num, ok = skewybox.get_value()
  4722. if ok:
  4723. # first get a bounding box to fit all
  4724. for obj in obj_list:
  4725. xmin, ymin, xmax, ymax = obj.bounds()
  4726. xminlist.append(xmin)
  4727. yminlist.append(ymin)
  4728. # get the minimum x,y and maximum x,y for all objects selected
  4729. xminimal = min(xminlist)
  4730. yminimal = min(yminlist)
  4731. for obj in obj_list:
  4732. obj.skew(0, num, point=(xminimal, yminimal))
  4733. obj.plot()
  4734. self.app_obj.object_changed.emit(obj)
  4735. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4736. def on_plots_updated(self):
  4737. """
  4738. Callback used to report when the plots have changed.
  4739. Adjust axes and zooms to fit.
  4740. :return: None
  4741. """
  4742. if self.is_legacy is False:
  4743. self.plotcanvas.update()
  4744. else:
  4745. self.plotcanvas.auto_adjust_axes()
  4746. self.on_zoom_fit()
  4747. self.collection.update_view()
  4748. # self.inform.emit(_("Plots updated ..."))
  4749. def on_toolbar_replot(self):
  4750. """
  4751. Callback for toolbar button. Re-plots all objects.
  4752. :return: None
  4753. """
  4754. self.defaults.report_usage("on_toolbar_replot")
  4755. self.log.debug("on_toolbar_replot()")
  4756. try:
  4757. self.collection.get_active().read_form()
  4758. except AttributeError:
  4759. self.log.debug("on_toolbar_replot(): AttributeError")
  4760. pass
  4761. self.plot_all()
  4762. def grid_status(self):
  4763. return True if self.ui.grid_snap_btn.isChecked() else False
  4764. def populate_cmenu_grids(self):
  4765. units = self.defaults['units'].lower()
  4766. # for act in self.ui.cmenu_gridmenu.actions():
  4767. # act.triggered.disconnect()
  4768. self.ui.cmenu_gridmenu.clear()
  4769. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4770. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4771. _("Grid On/Off"))
  4772. grid_toggle.setCheckable(True)
  4773. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4774. self.ui.cmenu_gridmenu.addSeparator()
  4775. for grid in sorted_list:
  4776. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4777. "%s" % str(grid))
  4778. action.triggered.connect(self.set_grid)
  4779. self.ui.cmenu_gridmenu.addSeparator()
  4780. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4781. _("Add"))
  4782. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4783. _("Delete"))
  4784. grid_add.triggered.connect(self.on_grid_add)
  4785. grid_delete.triggered.connect(self.on_grid_delete)
  4786. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4787. def set_grid(self):
  4788. menu_action = self.sender()
  4789. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4790. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4791. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4792. def on_grid_add(self):
  4793. # ## Current application units in lower Case
  4794. units = self.defaults['units'].lower()
  4795. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4796. text=_('Enter a Grid Value:'),
  4797. min=0.0000, max=99.9999, decimals=4)
  4798. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4799. val, ok = grid_add_popup.get_value()
  4800. if ok:
  4801. if float(val) == 0:
  4802. self.inform.emit('[WARNING_NOTCL] %s' %
  4803. _("Please enter a grid value with non-zero value, in Float format."))
  4804. return
  4805. else:
  4806. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4807. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4808. self.inform.emit('[success] %s...' % _("New Grid added"))
  4809. else:
  4810. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4811. else:
  4812. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4813. def on_grid_delete(self):
  4814. # ## Current application units in lower Case
  4815. units = self.defaults['units'].lower()
  4816. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4817. text='Enter a Grid Value:',
  4818. min=0.0000, max=99.9999, decimals=4)
  4819. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4820. val, ok = grid_del_popup.get_value()
  4821. if ok:
  4822. if float(val) == 0:
  4823. self.inform.emit('[WARNING_NOTCL] %s' %
  4824. _("Please enter a grid value with non-zero value, in Float format."))
  4825. return
  4826. else:
  4827. try:
  4828. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4829. except ValueError:
  4830. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4831. return
  4832. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4833. else:
  4834. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4835. def on_shortcut_list(self):
  4836. self.defaults.report_usage("on_shortcut_list()")
  4837. # add the tab if it was closed
  4838. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4839. # delete the absolute and relative position and messages in the infobar
  4840. self.ui.position_label.setText("")
  4841. # self.ui.rel_position_label.setText("")
  4842. # Switch plot_area to preferences page
  4843. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4844. # self.ui.show()
  4845. def on_select_tab(self, name):
  4846. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4847. if self.ui.splitter.sizes()[0] == 0:
  4848. self.ui.splitter.setSizes([1, 1])
  4849. else:
  4850. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4851. self.ui.splitter.setSizes([0, 1])
  4852. if name == 'project':
  4853. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4854. elif name == 'selected':
  4855. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4856. elif name == 'tool':
  4857. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4858. def on_copy_name(self):
  4859. self.defaults.report_usage("on_copy_name()")
  4860. obj = self.collection.get_active()
  4861. try:
  4862. name = obj.options["name"]
  4863. except AttributeError:
  4864. log.debug("on_copy_name() --> No object selected to copy it's name")
  4865. self.inform.emit('[WARNING_NOTCL]%s' %
  4866. _(" No object selected to copy it's name"))
  4867. return
  4868. self.clipboard.setText(name)
  4869. self.inform.emit(_("Name copied on clipboard ..."))
  4870. def on_mouse_click_over_plot(self, event):
  4871. """
  4872. Default actions are:
  4873. :param event: Contains information about the event, like which button
  4874. was clicked, the pixel coordinates and the axes coordinates.
  4875. :return: None
  4876. """
  4877. self.pos = []
  4878. if self.is_legacy is False:
  4879. event_pos = event.pos
  4880. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4881. # # Set the mouse button for panning
  4882. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4883. else:
  4884. event_pos = (event.xdata, event.ydata)
  4885. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4886. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4887. # So it can receive key presses
  4888. self.plotcanvas.native.setFocus()
  4889. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4890. if self.grid_status():
  4891. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4892. else:
  4893. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4894. try:
  4895. if event.button == 1:
  4896. # Reset here the relative coordinates so there is a new reference on the click position
  4897. if self.rel_point1 is None:
  4898. self.rel_point1 = self.pos
  4899. else:
  4900. self.rel_point2 = copy(self.rel_point1)
  4901. self.rel_point1 = self.pos
  4902. self.on_mouse_move_over_plot(event, origin_click=True)
  4903. except Exception as e:
  4904. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4905. def on_mouse_double_click_over_plot(self, event):
  4906. if event.button == 1:
  4907. self.doubleclick = True
  4908. def on_mouse_move_over_plot(self, event, origin_click=None):
  4909. """
  4910. Callback for the mouse motion event over the plot.
  4911. :param event: Contains information about the event.
  4912. :param origin_click
  4913. :return: None
  4914. """
  4915. if self.is_legacy is False:
  4916. event_pos = event.pos
  4917. if self.defaults["global_pan_button"] == '2':
  4918. pan_button = 2
  4919. else:
  4920. pan_button = 3
  4921. self.event_is_dragging = event.is_dragging
  4922. else:
  4923. event_pos = (event.xdata, event.ydata)
  4924. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4925. if self.defaults["global_pan_button"] == '2':
  4926. pan_button = 3
  4927. else:
  4928. pan_button = 2
  4929. self.event_is_dragging = self.plotcanvas.is_dragging
  4930. # So it can receive key presses but not when the Tcl Shell is active
  4931. if not self.ui.shell_dock.isVisible():
  4932. if not self.plotcanvas.native.hasFocus():
  4933. self.plotcanvas.native.setFocus()
  4934. self.pos_jump = event_pos
  4935. self.ui.popMenu.mouse_is_panning = False
  4936. if origin_click is None:
  4937. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4938. if event.button == pan_button and self.event_is_dragging == 1:
  4939. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4940. if self.ui.popMenu.popup_active:
  4941. self.ui.popMenu.popup_active = False
  4942. return
  4943. self.ui.popMenu.mouse_is_panning = True
  4944. return
  4945. if self.rel_point1 is not None:
  4946. try: # May fail in case mouse not within axes
  4947. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4948. if pos_canvas[0] is None or pos_canvas[1] is None:
  4949. return
  4950. if self.grid_status():
  4951. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4952. # Update cursor
  4953. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4954. symbol='++', edge_color=self.cursor_color_3D,
  4955. edge_width=self.defaults["global_cursor_width"],
  4956. size=self.defaults["global_cursor_size"])
  4957. else:
  4958. pos = (pos_canvas[0], pos_canvas[1])
  4959. self.dx = pos[0] - float(self.rel_point1[0])
  4960. self.dy = pos[1] - float(self.rel_point1[1])
  4961. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4962. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4963. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4964. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4965. units = self.defaults["units"].lower()
  4966. self.plotcanvas.text_hud.text = \
  4967. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4968. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4969. self.mouse = [pos[0], pos[1]]
  4970. # if the mouse is moved and the LMB is clicked then the action is a selection
  4971. if self.event_is_dragging == 1 and event.button == 1:
  4972. self.delete_selection_shape()
  4973. if self.dx < 0:
  4974. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4975. face_color=self.defaults['global_alt_sel_fill'])
  4976. self.selection_type = False
  4977. elif self.dx >= 0:
  4978. self.draw_moving_selection_shape(self.pos, pos)
  4979. self.selection_type = True
  4980. else:
  4981. self.selection_type = None
  4982. else:
  4983. self.selection_type = None
  4984. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4985. if self.defaults['global_hover']:
  4986. for obj in self.collection.get_list():
  4987. try:
  4988. # select the object(s) only if it is enabled (plotted)
  4989. if obj.options['plot']:
  4990. if obj not in self.collection.get_selected():
  4991. poly_obj = Polygon(
  4992. [(obj.options['xmin'], obj.options['ymin']),
  4993. (obj.options['xmax'], obj.options['ymin']),
  4994. (obj.options['xmax'], obj.options['ymax']),
  4995. (obj.options['xmin'], obj.options['ymax'])]
  4996. )
  4997. if Point(pos).within(poly_obj):
  4998. if obj.isHovering is False:
  4999. obj.isHovering = True
  5000. obj.notHovering = True
  5001. # create the selection box around the selected object
  5002. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5003. else:
  5004. if obj.notHovering is True:
  5005. obj.notHovering = False
  5006. obj.isHovering = False
  5007. self.delete_hover_shape()
  5008. except Exception:
  5009. # the Exception here will happen if we try to select on screen and we have an
  5010. # newly (and empty) just created Geometry or Excellon object that do not have the
  5011. # xmin, xmax, ymin, ymax options.
  5012. # In this case poly_obj creation (see above) will fail
  5013. pass
  5014. except Exception as e:
  5015. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5016. self.ui.position_label.setText("")
  5017. # self.ui.rel_position_label.setText("")
  5018. self.mouse = None
  5019. def on_mouse_click_release_over_plot(self, event):
  5020. """
  5021. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5022. and has been registered in ''self.__init__()''.
  5023. :param event: contains information about the event.
  5024. :return:
  5025. """
  5026. if self.is_legacy is False:
  5027. event_pos = event.pos
  5028. right_button = 2
  5029. else:
  5030. event_pos = (event.xdata, event.ydata)
  5031. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5032. right_button = 3
  5033. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5034. if self.grid_status():
  5035. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5036. else:
  5037. pos = (pos_canvas[0], pos_canvas[1])
  5038. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5039. # canvas menu
  5040. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5041. self.ui.popMenu.mouse_is_panning = False
  5042. self.cursor = QtGui.QCursor()
  5043. self.populate_cmenu_grids()
  5044. self.ui.popMenu.popup(self.cursor.pos())
  5045. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5046. # selection and then select a type of selection ("enclosing" or "touching")
  5047. if event.button == 1: # left click
  5048. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5049. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5050. if modifiers == QtCore.Qt.ShiftModifier:
  5051. # do not auto open the Project Tab
  5052. self.click_noproject = True
  5053. self.clipboard.setText(
  5054. self.defaults["global_point_clipboard_format"] %
  5055. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5056. )
  5057. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5058. return
  5059. if self.doubleclick is True:
  5060. self.doubleclick = False
  5061. if self.collection.get_selected():
  5062. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5063. if self.ui.splitter.sizes()[0] == 0:
  5064. self.ui.splitter.setSizes([1, 1])
  5065. try:
  5066. # delete the selection shape(S) as it may be in the way
  5067. self.delete_selection_shape()
  5068. self.delete_hover_shape()
  5069. except Exception as e:
  5070. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5071. return
  5072. else:
  5073. # WORKAROUND for LEGACY MODE
  5074. if self.is_legacy is True:
  5075. # if there is no move on canvas then we have no dragging selection
  5076. if self.dx == 0 or self.dy == 0:
  5077. self.selection_type = None
  5078. if self.selection_type is not None:
  5079. try:
  5080. self.selection_area_handler(self.pos, pos, self.selection_type)
  5081. self.selection_type = None
  5082. except Exception as e:
  5083. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5084. return
  5085. else:
  5086. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5087. if key_modifier == QtCore.Qt.ShiftModifier:
  5088. mod_key = 'Shift'
  5089. elif key_modifier == QtCore.Qt.ControlModifier:
  5090. mod_key = 'Control'
  5091. else:
  5092. mod_key = None
  5093. try:
  5094. if self.command_active is None:
  5095. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5096. # deselect, and if it's not selected then it will be selected
  5097. # If there is no active command (self.command_active is None) then we check if we clicked
  5098. # on a object by checking the bounding limits against mouse click position
  5099. if mod_key == self.defaults["global_mselect_key"]:
  5100. self.select_objects(key='multisel')
  5101. else:
  5102. # If there is no active command (self.command_active is None) then we check if
  5103. # we clicked on a object by checking the bounding limits against mouse click position
  5104. self.select_objects()
  5105. self.delete_hover_shape()
  5106. except Exception as e:
  5107. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5108. return
  5109. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5110. """
  5111. :param start_pos: mouse position when the selection LMB click was done
  5112. :param end_pos: mouse position when the left mouse button is released
  5113. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5114. :return:
  5115. """
  5116. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5117. # delete previous selection shape
  5118. self.delete_selection_shape()
  5119. # make all objects inactive
  5120. self.collection.set_all_inactive()
  5121. for obj in self.collection.get_list():
  5122. try:
  5123. # select the object(s) only if it is enabled (plotted)
  5124. if obj.options['plot']:
  5125. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5126. (obj.options['xmax'], obj.options['ymin']),
  5127. (obj.options['xmax'], obj.options['ymax']),
  5128. (obj.options['xmin'], obj.options['ymax'])])
  5129. if sel_type is True:
  5130. if poly_obj.within(poly_selection):
  5131. # create the selection box around the selected object
  5132. if self.defaults['global_selection_shape'] is True:
  5133. self.draw_selection_shape(obj)
  5134. self.collection.set_active(obj.options['name'])
  5135. else:
  5136. if poly_selection.intersects(poly_obj):
  5137. # create the selection box around the selected object
  5138. if self.defaults['global_selection_shape'] is True:
  5139. self.draw_selection_shape(obj)
  5140. self.collection.set_active(obj.options['name'])
  5141. obj.selection_shape_drawn = True
  5142. except Exception as e:
  5143. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5144. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5145. # In this case poly_obj creation (see above) will fail
  5146. log.debug("App.selection_area_handler() --> %s" % str(e))
  5147. def select_objects(self, key=None):
  5148. """
  5149. Will select objects clicked on canvas
  5150. :param key: for future use in cumulative selection
  5151. :return:
  5152. """
  5153. # list where we store the overlapped objects under our mouse left click position
  5154. if key is None:
  5155. self.objects_under_the_click_list = []
  5156. # Populate the list with the overlapped objects on the click position
  5157. curr_x, curr_y = self.pos
  5158. for obj in self.all_objects_list:
  5159. # ScriptObject and DocumentObject objects can't be selected
  5160. if obj.kind == 'script' or obj.kind == 'document':
  5161. continue
  5162. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5163. continue
  5164. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5165. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5166. if obj.options['name'] not in self.objects_under_the_click_list:
  5167. if obj.options['plot']:
  5168. # add objects to the objects_under_the_click list only if the object is plotted
  5169. # (active and not disabled)
  5170. self.objects_under_the_click_list.append(obj.options['name'])
  5171. try:
  5172. if self.objects_under_the_click_list:
  5173. curr_sel_obj = self.collection.get_active()
  5174. # case when there is only an object under the click and we toggle it
  5175. if len(self.objects_under_the_click_list) == 1:
  5176. if curr_sel_obj is None:
  5177. self.collection.set_active(self.objects_under_the_click_list[0])
  5178. curr_sel_obj = self.collection.get_active()
  5179. # create the selection box around the selected object
  5180. if self.defaults['global_selection_shape'] is True:
  5181. self.draw_selection_shape(curr_sel_obj)
  5182. curr_sel_obj.selection_shape_drawn = True
  5183. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5184. self.collection.on_objects_selection(False)
  5185. self.delete_selection_shape()
  5186. curr_sel_obj.selection_shape_drawn = False
  5187. self.collection.set_active(self.objects_under_the_click_list[0])
  5188. curr_sel_obj = self.collection.get_active()
  5189. # create the selection box around the selected object
  5190. if self.defaults['global_selection_shape'] is True:
  5191. self.draw_selection_shape(curr_sel_obj)
  5192. curr_sel_obj.selection_shape_drawn = True
  5193. self.selected_message(curr_sel_obj=curr_sel_obj)
  5194. elif curr_sel_obj.selection_shape_drawn is False:
  5195. if self.defaults['global_selection_shape'] is True:
  5196. self.draw_selection_shape(curr_sel_obj)
  5197. curr_sel_obj.selection_shape_drawn = True
  5198. else:
  5199. self.collection.on_objects_selection(False)
  5200. self.delete_selection_shape()
  5201. if self.call_source != 'app':
  5202. self.call_source = 'app'
  5203. self.selected_message(curr_sel_obj=curr_sel_obj)
  5204. else:
  5205. # If there is no selected object
  5206. # make active the first element of the overlapped objects list
  5207. if self.collection.get_active() is None:
  5208. self.collection.set_active(self.objects_under_the_click_list[0])
  5209. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5210. name_sel_obj = self.collection.get_active().options['name']
  5211. # In case that there is a selected object but it is not in the overlapped object list
  5212. # make that object inactive and activate the first element in the overlapped object list
  5213. if name_sel_obj not in self.objects_under_the_click_list:
  5214. self.collection.set_inactive(name_sel_obj)
  5215. name_sel_obj = self.objects_under_the_click_list[0]
  5216. self.collection.set_active(name_sel_obj)
  5217. else:
  5218. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5219. self.collection.set_all_inactive()
  5220. self.collection.set_active(
  5221. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5222. curr_sel_obj = self.collection.get_active()
  5223. # delete the possible selection box around a possible selected object
  5224. self.delete_selection_shape()
  5225. curr_sel_obj.selection_shape_drawn = False
  5226. # create the selection box around the selected object
  5227. if self.defaults['global_selection_shape'] is True:
  5228. self.draw_selection_shape(curr_sel_obj)
  5229. curr_sel_obj.selection_shape_drawn = True
  5230. self.selected_message(curr_sel_obj=curr_sel_obj)
  5231. else:
  5232. # deselect everything
  5233. self.collection.on_objects_selection(False)
  5234. # delete the possible selection box around a possible selected object
  5235. self.delete_selection_shape()
  5236. for o in self.collection.get_list():
  5237. o.selection_shape_drawn = False
  5238. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5239. # only when working on App
  5240. if self.call_source == 'app':
  5241. if self.click_noproject is False:
  5242. # if the Tool Tab is in focus don't change focus to Project Tab
  5243. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5244. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5245. else:
  5246. # restore auto open the Project Tab
  5247. self.click_noproject = False
  5248. # delete any text in the status bar, implicitly the last object name that was selected
  5249. # self.inform.emit("")
  5250. else:
  5251. self.call_source = 'app'
  5252. except Exception as e:
  5253. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5254. def selected_message(self, curr_sel_obj):
  5255. if curr_sel_obj:
  5256. if curr_sel_obj.kind == 'gerber':
  5257. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5258. color='green',
  5259. name=str(curr_sel_obj.options['name']),
  5260. tx=_("selected"))
  5261. )
  5262. elif curr_sel_obj.kind == 'excellon':
  5263. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5264. color='brown',
  5265. name=str(curr_sel_obj.options['name']),
  5266. tx=_("selected"))
  5267. )
  5268. elif curr_sel_obj.kind == 'cncjob':
  5269. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5270. color='blue',
  5271. name=str(curr_sel_obj.options['name']),
  5272. tx=_("selected"))
  5273. )
  5274. elif curr_sel_obj.kind == 'geometry':
  5275. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5276. color='red',
  5277. name=str(curr_sel_obj.options['name']),
  5278. tx=_("selected"))
  5279. )
  5280. def delete_hover_shape(self):
  5281. self.hover_shapes.clear()
  5282. self.hover_shapes.redraw()
  5283. def draw_hover_shape(self, sel_obj, color=None):
  5284. """
  5285. :param sel_obj: The object for which the hover shape must be drawn
  5286. :param color: The color of the hover shape
  5287. :return: None
  5288. """
  5289. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5290. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5291. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5292. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5293. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5294. if self.defaults['units'].upper() == 'MM':
  5295. hover_rect = hover_rect.buffer(-0.1)
  5296. hover_rect = hover_rect.buffer(0.2)
  5297. else:
  5298. hover_rect = hover_rect.buffer(-0.00393)
  5299. hover_rect = hover_rect.buffer(0.00787)
  5300. # if color:
  5301. # face = Color(color)
  5302. # face.alpha = 0.2
  5303. # outline = Color(color, alpha=0.8)
  5304. # else:
  5305. # face = Color(self.defaults['global_sel_fill'])
  5306. # face.alpha = 0.2
  5307. # outline = self.defaults['global_sel_line']
  5308. if color:
  5309. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5310. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5311. else:
  5312. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5313. outline = self.defaults['global_sel_line']
  5314. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5315. if self.is_legacy is True:
  5316. self.hover_shapes.redraw()
  5317. def delete_selection_shape(self):
  5318. self.move_tool.sel_shapes.clear()
  5319. self.move_tool.sel_shapes.redraw()
  5320. def draw_selection_shape(self, sel_obj, color=None):
  5321. """
  5322. Will draw a selection shape around the selected object.
  5323. :param sel_obj: The object for which the selection shape must be drawn
  5324. :param color: The color for the selection shape.
  5325. :return: None
  5326. """
  5327. if sel_obj is None:
  5328. return
  5329. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5330. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5331. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5332. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5333. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5334. if self.defaults['units'].upper() == 'MM':
  5335. sel_rect = sel_rect.buffer(-0.1)
  5336. sel_rect = sel_rect.buffer(0.2)
  5337. else:
  5338. sel_rect = sel_rect.buffer(-0.00393)
  5339. sel_rect = sel_rect.buffer(0.00787)
  5340. if color:
  5341. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5342. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5343. else:
  5344. if self.is_legacy is False:
  5345. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5346. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5347. else:
  5348. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5349. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5350. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5351. color=outline,
  5352. face_color=face,
  5353. update=True,
  5354. layer=0,
  5355. tolerance=None))
  5356. if self.is_legacy is True:
  5357. self.move_tool.sel_shapes.redraw()
  5358. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5359. """
  5360. Will draw a selection shape when dragging mouse on canvas.
  5361. :param old_coords: Old coordinates
  5362. :param coords: New coordinates
  5363. :param kwargs: Keyword arguments
  5364. :return:
  5365. """
  5366. if 'color' in kwargs:
  5367. color = kwargs['color']
  5368. else:
  5369. color = self.defaults['global_sel_line']
  5370. if 'face_color' in kwargs:
  5371. face_color = kwargs['face_color']
  5372. else:
  5373. face_color = self.defaults['global_sel_fill']
  5374. if 'face_alpha' in kwargs:
  5375. face_alpha = kwargs['face_alpha']
  5376. else:
  5377. face_alpha = 0.3
  5378. x0, y0 = old_coords
  5379. x1, y1 = coords
  5380. pt1 = (x0, y0)
  5381. pt2 = (x1, y0)
  5382. pt3 = (x1, y1)
  5383. pt4 = (x0, y1)
  5384. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5385. # color_t = Color(face_color)
  5386. # color_t.alpha = face_alpha
  5387. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5388. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5389. layer=0, tolerance=None)
  5390. if self.is_legacy is True:
  5391. self.move_tool.sel_shapes.redraw()
  5392. def on_file_new_click(self):
  5393. """
  5394. Callback for menu item File -> New.
  5395. Executed on clicking the Menu -> File -> New Project
  5396. :return:
  5397. """
  5398. if self.collection.get_list() and self.should_we_save:
  5399. msgbox = QtWidgets.QMessageBox()
  5400. # msgbox.setText("<B>Save changes ...</B>")
  5401. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5402. "Creating a New project will delete them.\n"
  5403. "Do you want to Save the project?"))
  5404. msgbox.setWindowTitle(_("Save changes"))
  5405. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5406. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5407. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5408. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5409. msgbox.setDefaultButton(bt_yes)
  5410. msgbox.exec_()
  5411. response = msgbox.clickedButton()
  5412. if response == bt_yes:
  5413. self.on_file_saveprojectas()
  5414. elif response == bt_cancel:
  5415. return
  5416. elif response == bt_no:
  5417. self.on_file_new()
  5418. else:
  5419. self.on_file_new()
  5420. self.inform.emit('[success] %s...' % _("New Project created"))
  5421. def on_file_new(self, cli=None):
  5422. """
  5423. Returns the application to its startup state. This method is thread-safe.
  5424. :param cli: Boolean. If True this method was run from command line
  5425. :return: None
  5426. """
  5427. self.defaults.report_usage("on_file_new")
  5428. # Remove everything from memory
  5429. App.log.debug("on_file_new()")
  5430. # close any editor that might be open
  5431. if self.call_source != 'app':
  5432. self.editor2object(cleanup=True)
  5433. # ## EDITOR section
  5434. self.geo_editor = FlatCAMGeoEditor(self)
  5435. self.exc_editor = FlatCAMExcEditor(self)
  5436. self.grb_editor = FlatCAMGrbEditor(self)
  5437. # Clear pool
  5438. self.clear_pool()
  5439. for obj in self.collection.get_list():
  5440. # delete shapes left drawn from mark shape_collections, if any
  5441. if isinstance(obj, GerberObject):
  5442. try:
  5443. for el in obj.mark_shapes:
  5444. obj.mark_shapes[el].clear(update=True)
  5445. obj.mark_shapes[el].enabled = False
  5446. del el
  5447. except AttributeError:
  5448. pass
  5449. # also delete annotation shapes, if any
  5450. elif isinstance(obj, CNCJobObject):
  5451. try:
  5452. obj.text_col.enabled = False
  5453. del obj.text_col
  5454. obj.annotation.clear(update=True)
  5455. del obj.annotation
  5456. except AttributeError:
  5457. pass
  5458. # delete the exclusion areas
  5459. self.exc_areas.clear_shapes()
  5460. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5461. self.shell.init_tcl()
  5462. # delete any selection shape on canvas
  5463. self.delete_selection_shape()
  5464. # delete all FlatCAM objects
  5465. self.collection.delete_all()
  5466. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5467. self.setup_component_editor()
  5468. # Clear project filename
  5469. self.project_filename = None
  5470. # Load the application defaults
  5471. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5472. # Re-fresh project options
  5473. self.on_options_app2project()
  5474. # Init FlatCAMTools
  5475. self.init_tools()
  5476. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5477. if cli is None:
  5478. # we need to go in reverse because once we remove a tab then the index changes
  5479. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5480. # and so on. Therefore the deletion should be done in reverse
  5481. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5482. for index in range(wdg_count, -1, -1):
  5483. try:
  5484. self.ui.plot_tab_area.closeTab(index)
  5485. except Exception as e:
  5486. log.debug("App.on_file_new() --> %s" % str(e))
  5487. # # And then add again the Plot Area
  5488. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5489. self.ui.plot_tab_area.protectTab(0)
  5490. # take the focus of the Notebook on Project Tab.
  5491. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5492. self.set_ui_title(name=_("New Project - Not saved"))
  5493. def obj_properties(self):
  5494. """
  5495. Will launch the object Properties Tool
  5496. :return:
  5497. """
  5498. self.defaults.report_usage("obj_properties()")
  5499. self.properties_tool.run(toggle=False)
  5500. def on_project_context_save(self):
  5501. """
  5502. Wrapper, will save the object function of it's type
  5503. :return:
  5504. """
  5505. obj = self.collection.get_active()
  5506. if type(obj) == GeometryObject:
  5507. self.on_file_exportdxf()
  5508. elif type(obj) == ExcellonObject:
  5509. self.on_file_saveexcellon()
  5510. elif type(obj) == CNCJobObject:
  5511. obj.on_exportgcode_button_click()
  5512. elif type(obj) == GerberObject:
  5513. self.on_file_savegerber()
  5514. elif type(obj) == ScriptObject:
  5515. self.on_file_savescript()
  5516. elif type(obj) == DocumentObject:
  5517. self.on_file_savedocument()
  5518. def obj_move(self):
  5519. """
  5520. Callback for the Move menu entry in various Context Menu's.
  5521. :return:
  5522. """
  5523. self.defaults.report_usage("obj_move()")
  5524. self.move_tool.run(toggle=False)
  5525. def on_fileopengerber(self, signal, name=None):
  5526. """
  5527. File menu callback for opening a Gerber.
  5528. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5529. :param name:
  5530. :return: None
  5531. """
  5532. self.defaults.report_usage("on_fileopengerber")
  5533. App.log.debug("on_fileopengerber()")
  5534. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5535. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5536. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5537. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5538. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5539. "*.mil);;" \
  5540. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5541. "Allegro Files (*.art);;" \
  5542. "Mentor Files (*.pho *.gdo);;" \
  5543. "All Files (*.*)"
  5544. if name is None:
  5545. try:
  5546. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5547. directory=self.get_last_folder(),
  5548. filter=_filter_)
  5549. except TypeError:
  5550. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5551. filenames = [str(filename) for filename in filenames]
  5552. else:
  5553. filenames = [name]
  5554. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5555. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5556. _("Opening Gerber file.")),
  5557. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5558. color=QtGui.QColor("gray"))
  5559. if len(filenames) == 0:
  5560. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5561. else:
  5562. for filename in filenames:
  5563. if filename != '':
  5564. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5565. def on_fileopenexcellon(self, signal, name=None):
  5566. """
  5567. File menu callback for opening an Excellon file.
  5568. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5569. :param name:
  5570. :return: None
  5571. """
  5572. self.defaults.report_usage("on_fileopenexcellon")
  5573. App.log.debug("on_fileopenexcellon()")
  5574. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5575. "All Files (*.*)"
  5576. if name is None:
  5577. try:
  5578. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5579. directory=self.get_last_folder(),
  5580. filter=_filter_)
  5581. except TypeError:
  5582. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5583. filenames = [str(filename) for filename in filenames]
  5584. else:
  5585. filenames = [str(name)]
  5586. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5587. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5588. _("Opening Excellon file.")),
  5589. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5590. color=QtGui.QColor("gray"))
  5591. if len(filenames) == 0:
  5592. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5593. else:
  5594. for filename in filenames:
  5595. if filename != '':
  5596. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5597. def on_fileopengcode(self, signal, name=None):
  5598. """
  5599. File menu call back for opening gcode.
  5600. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5601. :param name:
  5602. :return:
  5603. """
  5604. self.defaults.report_usage("on_fileopengcode")
  5605. App.log.debug("on_fileopengcode()")
  5606. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5607. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5608. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5609. "All Files (*.*)"
  5610. if name is None:
  5611. try:
  5612. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5613. directory=self.get_last_folder(),
  5614. filter=_filter_)
  5615. except TypeError:
  5616. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5617. filenames = [str(filename) for filename in filenames]
  5618. else:
  5619. filenames = [name]
  5620. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5621. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5622. _("Opening G-Code file.")),
  5623. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5624. color=QtGui.QColor("gray"))
  5625. if len(filenames) == 0:
  5626. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5627. else:
  5628. for filename in filenames:
  5629. if filename != '':
  5630. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5631. def on_file_openproject(self, signal):
  5632. """
  5633. File menu callback for opening a project.
  5634. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5635. :return: None
  5636. """
  5637. self.defaults.report_usage("on_file_openproject")
  5638. App.log.debug("on_file_openproject()")
  5639. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5640. try:
  5641. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5642. directory=self.get_last_folder(), filter=_filter_)
  5643. except TypeError:
  5644. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5645. # The Qt methods above will return a QString which can cause problems later.
  5646. # So far json.dump() will fail to serialize it.
  5647. # TODO: Improve the serialization methods and remove this fix.
  5648. filename = str(filename)
  5649. if filename == "":
  5650. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5651. else:
  5652. # self.worker_task.emit({'fcn': self.open_project,
  5653. # 'params': [filename]})
  5654. # The above was failing because open_project() is not
  5655. # thread safe. The new_project()
  5656. self.open_project(filename)
  5657. def on_fileopenhpgl2(self, signal, name=None):
  5658. """
  5659. File menu callback for opening a HPGL2.
  5660. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5661. :param name:
  5662. :return: None
  5663. """
  5664. self.defaults.report_usage("on_fileopenhpgl2")
  5665. App.log.debug("on_fileopenhpgl2()")
  5666. _filter_ = "HPGL2 Files (*.plt);;" \
  5667. "All Files (*.*)"
  5668. if name is None:
  5669. try:
  5670. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5671. directory=self.get_last_folder(),
  5672. filter=_filter_)
  5673. except TypeError:
  5674. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5675. filenames = [str(filename) for filename in filenames]
  5676. else:
  5677. filenames = [name]
  5678. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5679. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5680. _("Opening HPGL2 file.")),
  5681. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5682. color=QtGui.QColor("gray"))
  5683. if len(filenames) == 0:
  5684. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5685. else:
  5686. for filename in filenames:
  5687. if filename != '':
  5688. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5689. def on_file_openconfig(self, signal):
  5690. """
  5691. File menu callback for opening a config file.
  5692. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5693. :return: None
  5694. """
  5695. self.defaults.report_usage("on_file_openconfig")
  5696. App.log.debug("on_file_openconfig()")
  5697. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5698. try:
  5699. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5700. directory=self.data_path, filter=_filter_)
  5701. except TypeError:
  5702. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5703. filter=_filter_)
  5704. if filename == "":
  5705. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5706. else:
  5707. self.open_config_file(filename)
  5708. def on_file_exportsvg(self):
  5709. """
  5710. Callback for menu item File->Export SVG.
  5711. :return: None
  5712. """
  5713. self.defaults.report_usage("on_file_exportsvg")
  5714. App.log.debug("on_file_exportsvg()")
  5715. obj = self.collection.get_active()
  5716. if obj is None:
  5717. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5718. msg = _("Please Select a Geometry object to export")
  5719. msgbox = QtWidgets.QMessageBox()
  5720. msgbox.setInformativeText(msg)
  5721. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5722. msgbox.setDefaultButton(bt_ok)
  5723. msgbox.exec_()
  5724. return
  5725. # Check for more compatible types and add as required
  5726. if (not isinstance(obj, GeometryObject)
  5727. and not isinstance(obj, GerberObject)
  5728. and not isinstance(obj, CNCJobObject)
  5729. and not isinstance(obj, ExcellonObject)):
  5730. msg = '[ERROR_NOTCL] %s' % \
  5731. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5732. msgbox = QtWidgets.QMessageBox()
  5733. msgbox.setInformativeText(msg)
  5734. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5735. msgbox.setDefaultButton(bt_ok)
  5736. msgbox.exec_()
  5737. return
  5738. name = obj.options["name"]
  5739. _filter = "SVG File (*.svg);;All Files (*.*)"
  5740. try:
  5741. filename, _f = FCFileSaveDialog.get_saved_filename(
  5742. caption=_("Export SVG"),
  5743. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5744. filter=_filter)
  5745. except TypeError:
  5746. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5747. filename = str(filename)
  5748. if filename == "":
  5749. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5750. return
  5751. else:
  5752. self.export_svg(name, filename)
  5753. if self.defaults["global_open_style"] is False:
  5754. self.file_opened.emit("SVG", filename)
  5755. self.file_saved.emit("SVG", filename)
  5756. def on_file_exportpng(self):
  5757. self.defaults.report_usage("on_file_exportpng")
  5758. App.log.debug("on_file_exportpng()")
  5759. self.date = str(datetime.today()).rpartition('.')[0]
  5760. self.date = ''.join(c for c in self.date if c not in ':-')
  5761. self.date = self.date.replace(' ', '_')
  5762. if self.is_legacy is False:
  5763. image = _screenshot()
  5764. data = np.asarray(image)
  5765. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5766. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5767. return
  5768. filter_ = "PNG File (*.png);;All Files (*.*)"
  5769. try:
  5770. filename, _f = FCFileSaveDialog.get_saved_filename(
  5771. caption=_("Export PNG Image"),
  5772. directory=self.get_last_save_folder() + '/png_' + self.date,
  5773. filter=filter_)
  5774. except TypeError:
  5775. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5776. filename = str(filename)
  5777. if filename == "":
  5778. self.inform.emit(_("Cancelled."))
  5779. return
  5780. else:
  5781. if self.is_legacy is False:
  5782. write_png(filename, data)
  5783. else:
  5784. self.plotcanvas.figure.savefig(filename)
  5785. if self.defaults["global_open_style"] is False:
  5786. self.file_opened.emit("png", filename)
  5787. self.file_saved.emit("png", filename)
  5788. def on_file_savegerber(self):
  5789. """
  5790. Callback for menu item in Project context menu.
  5791. :return: None
  5792. """
  5793. self.defaults.report_usage("on_file_savegerber")
  5794. App.log.debug("on_file_savegerber()")
  5795. obj = self.collection.get_active()
  5796. if obj is None:
  5797. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5798. return
  5799. # Check for more compatible types and add as required
  5800. if not isinstance(obj, GerberObject):
  5801. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5802. return
  5803. name = self.collection.get_active().options["name"]
  5804. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5805. try:
  5806. filename, _f = FCFileSaveDialog.get_saved_filename(
  5807. caption="Save Gerber source file",
  5808. directory=self.get_last_save_folder() + '/' + name,
  5809. filter=_filter)
  5810. except TypeError:
  5811. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5812. filename = str(filename)
  5813. if filename == "":
  5814. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5815. return
  5816. else:
  5817. self.save_source_file(name, filename)
  5818. if self.defaults["global_open_style"] is False:
  5819. self.file_opened.emit("Gerber", filename)
  5820. self.file_saved.emit("Gerber", filename)
  5821. def on_file_savescript(self):
  5822. """
  5823. Callback for menu item in Project context menu.
  5824. :return: None
  5825. """
  5826. self.defaults.report_usage("on_file_savescript")
  5827. App.log.debug("on_file_savescript()")
  5828. obj = self.collection.get_active()
  5829. if obj is None:
  5830. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5831. return
  5832. # Check for more compatible types and add as required
  5833. if not isinstance(obj, ScriptObject):
  5834. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5835. return
  5836. name = self.collection.get_active().options["name"]
  5837. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5838. try:
  5839. filename, _f = FCFileSaveDialog.get_saved_filename(
  5840. caption="Save Script source file",
  5841. directory=self.get_last_save_folder() + '/' + name,
  5842. filter=_filter)
  5843. except TypeError:
  5844. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5845. filename = str(filename)
  5846. if filename == "":
  5847. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5848. return
  5849. else:
  5850. self.save_source_file(name, filename)
  5851. if self.defaults["global_open_style"] is False:
  5852. self.file_opened.emit("Script", filename)
  5853. self.file_saved.emit("Script", filename)
  5854. def on_file_savedocument(self):
  5855. """
  5856. Callback for menu item in Project context menu.
  5857. :return: None
  5858. """
  5859. self.defaults.report_usage("on_file_savedocument")
  5860. App.log.debug("on_file_savedocument()")
  5861. obj = self.collection.get_active()
  5862. if obj is None:
  5863. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5864. return
  5865. # Check for more compatible types and add as required
  5866. if not isinstance(obj, ScriptObject):
  5867. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5868. return
  5869. name = self.collection.get_active().options["name"]
  5870. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5871. try:
  5872. filename, _f = FCFileSaveDialog.get_saved_filename(
  5873. caption="Save Document source file",
  5874. directory=self.get_last_save_folder() + '/' + name,
  5875. filter=_filter)
  5876. except TypeError:
  5877. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5878. filename = str(filename)
  5879. if filename == "":
  5880. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5881. return
  5882. else:
  5883. self.save_source_file(name, filename)
  5884. if self.defaults["global_open_style"] is False:
  5885. self.file_opened.emit("Document", filename)
  5886. self.file_saved.emit("Document", filename)
  5887. def on_file_saveexcellon(self):
  5888. """
  5889. Callback for menu item in project context menu.
  5890. :return: None
  5891. """
  5892. self.defaults.report_usage("on_file_saveexcellon")
  5893. App.log.debug("on_file_saveexcellon()")
  5894. obj = self.collection.get_active()
  5895. if obj is None:
  5896. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5897. return
  5898. # Check for more compatible types and add as required
  5899. if not isinstance(obj, ExcellonObject):
  5900. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5901. return
  5902. name = self.collection.get_active().options["name"]
  5903. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5904. try:
  5905. filename, _f = FCFileSaveDialog.get_saved_filename(
  5906. caption=_("Save Excellon source file"),
  5907. directory=self.get_last_save_folder() + '/' + name,
  5908. filter=_filter)
  5909. except TypeError:
  5910. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5911. filename = str(filename)
  5912. if filename == "":
  5913. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5914. return
  5915. else:
  5916. self.save_source_file(name, filename)
  5917. if self.defaults["global_open_style"] is False:
  5918. self.file_opened.emit("Excellon", filename)
  5919. self.file_saved.emit("Excellon", filename)
  5920. def on_file_exportexcellon(self):
  5921. """
  5922. Callback for menu item File->Export->Excellon.
  5923. :return: None
  5924. """
  5925. self.defaults.report_usage("on_file_exportexcellon")
  5926. App.log.debug("on_file_exportexcellon()")
  5927. obj = self.collection.get_active()
  5928. if obj is None:
  5929. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5930. return
  5931. # Check for more compatible types and add as required
  5932. if not isinstance(obj, ExcellonObject):
  5933. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5934. return
  5935. name = self.collection.get_active().options["name"]
  5936. _filter = self.defaults["excellon_save_filters"]
  5937. try:
  5938. filename, _f = FCFileSaveDialog.get_saved_filename(
  5939. caption=_("Export Excellon"),
  5940. directory=self.get_last_save_folder() + '/' + name,
  5941. filter=_filter)
  5942. except TypeError:
  5943. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5944. filename = str(filename)
  5945. if filename == "":
  5946. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5947. return
  5948. else:
  5949. used_extension = filename.rpartition('.')[2]
  5950. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5951. self.export_excellon(name, filename)
  5952. if self.defaults["global_open_style"] is False:
  5953. self.file_opened.emit("Excellon", filename)
  5954. self.file_saved.emit("Excellon", filename)
  5955. def on_file_exportgerber(self):
  5956. """
  5957. Callback for menu item File->Export->Gerber.
  5958. :return: None
  5959. """
  5960. self.defaults.report_usage("on_file_exportgerber")
  5961. App.log.debug("on_file_exportgerber()")
  5962. obj = self.collection.get_active()
  5963. if obj is None:
  5964. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5965. return
  5966. # Check for more compatible types and add as required
  5967. if not isinstance(obj, GerberObject):
  5968. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5969. return
  5970. name = self.collection.get_active().options["name"]
  5971. _filter_ = self.defaults['gerber_save_filters']
  5972. try:
  5973. filename, _f = FCFileSaveDialog.get_saved_filename(
  5974. caption=_("Export Gerber"),
  5975. directory=self.get_last_save_folder() + '/' + name,
  5976. filter=_filter_)
  5977. except TypeError:
  5978. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5979. filename = str(filename)
  5980. if filename == "":
  5981. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5982. return
  5983. else:
  5984. used_extension = filename.rpartition('.')[2]
  5985. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5986. self.export_gerber(name, filename)
  5987. if self.defaults["global_open_style"] is False:
  5988. self.file_opened.emit("Gerber", filename)
  5989. self.file_saved.emit("Gerber", filename)
  5990. def on_file_exportdxf(self):
  5991. """
  5992. Callback for menu item File->Export DXF.
  5993. :return: None
  5994. """
  5995. self.defaults.report_usage("on_file_exportdxf")
  5996. App.log.debug("on_file_exportdxf()")
  5997. obj = self.collection.get_active()
  5998. if obj is None:
  5999. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6000. msg = _("Please Select a Geometry object to export")
  6001. msgbox = QtWidgets.QMessageBox()
  6002. msgbox.setInformativeText(msg)
  6003. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6004. msgbox.setDefaultButton(bt_ok)
  6005. msgbox.exec_()
  6006. return
  6007. # Check for more compatible types and add as required
  6008. if not isinstance(obj, GeometryObject):
  6009. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6010. msgbox = QtWidgets.QMessageBox()
  6011. msgbox.setInformativeText(msg)
  6012. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6013. msgbox.setDefaultButton(bt_ok)
  6014. msgbox.exec_()
  6015. return
  6016. name = self.collection.get_active().options["name"]
  6017. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6018. try:
  6019. filename, _f = FCFileSaveDialog.get_saved_filename(
  6020. caption=_("Export DXF"),
  6021. directory=self.get_last_save_folder() + '/' + name,
  6022. filter=_filter_)
  6023. except TypeError:
  6024. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6025. filename = str(filename)
  6026. if filename == "":
  6027. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6028. return
  6029. else:
  6030. self.export_dxf(name, filename)
  6031. if self.defaults["global_open_style"] is False:
  6032. self.file_opened.emit("DXF", filename)
  6033. self.file_saved.emit("DXF", filename)
  6034. def on_file_importsvg(self, type_of_obj):
  6035. """
  6036. Callback for menu item File->Import SVG.
  6037. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6038. :type type_of_obj: str
  6039. :return: None
  6040. """
  6041. self.defaults.report_usage("on_file_importsvg")
  6042. App.log.debug("on_file_importsvg()")
  6043. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6044. try:
  6045. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6046. directory=self.get_last_folder(), filter=_filter_)
  6047. except TypeError:
  6048. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6049. filter=_filter_)
  6050. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6051. type_of_obj = "geometry"
  6052. filenames = [str(filename) for filename in filenames]
  6053. if len(filenames) == 0:
  6054. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6055. else:
  6056. for filename in filenames:
  6057. if filename != '':
  6058. self.worker_task.emit({'fcn': self.import_svg,
  6059. 'params': [filename, type_of_obj]})
  6060. def on_file_importdxf(self, type_of_obj):
  6061. """
  6062. Callback for menu item File->Import DXF.
  6063. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6064. :type type_of_obj: str
  6065. :return: None
  6066. """
  6067. self.defaults.report_usage("on_file_importdxf")
  6068. App.log.debug("on_file_importdxf()")
  6069. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6070. try:
  6071. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6072. directory=self.get_last_folder(),
  6073. filter=_filter_)
  6074. except TypeError:
  6075. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6076. filter=_filter_)
  6077. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6078. type_of_obj = "geometry"
  6079. filenames = [str(filename) for filename in filenames]
  6080. if len(filenames) == 0:
  6081. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6082. else:
  6083. for filename in filenames:
  6084. if filename != '':
  6085. self.worker_task.emit({'fcn': self.import_dxf,
  6086. 'params': [filename, type_of_obj]})
  6087. # ###############################################################################################################
  6088. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6089. # ###############################################################################################################
  6090. def init_code_editor(self, name):
  6091. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6092. # add the tab if it was closed
  6093. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6094. self.text_editor_tab.setObjectName('text_editor_tab')
  6095. # delete the absolute and relative position and messages in the infobar
  6096. self.ui.position_label.setText("")
  6097. # self.ui.rel_position_label.setText("")
  6098. # first clear previous text in text editor (if any)
  6099. self.text_editor_tab.code_editor.clear()
  6100. self.text_editor_tab.code_editor.setReadOnly(False)
  6101. self.toggle_codeeditor = True
  6102. self.text_editor_tab.code_editor.completer_enable = False
  6103. self.text_editor_tab.buttonRun.hide()
  6104. # make sure to keep a reference to the code editor
  6105. self.reference_code_editor = self.text_editor_tab.code_editor
  6106. # Switch plot_area to CNCJob tab
  6107. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6108. def on_view_source(self):
  6109. """
  6110. Called when the user wants to see the source file of the selected object
  6111. :return:
  6112. """
  6113. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6114. self.proc_container.view.set_busy(_("Loading..."))
  6115. try:
  6116. obj = self.collection.get_active()
  6117. except Exception as e:
  6118. log.debug("App.on_view_source() --> %s" % str(e))
  6119. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6120. return 'fail'
  6121. if obj is None:
  6122. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6123. return 'fail'
  6124. flt = "All Files (*.*)"
  6125. if obj.kind == 'gerber':
  6126. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6127. elif obj.kind == 'excellon':
  6128. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6129. elif obj.kind == 'cncjob':
  6130. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6131. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6132. # add the tab if it was closed
  6133. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6134. self.source_editor_tab.setObjectName('source_editor_tab')
  6135. # delete the absolute and relative position and messages in the infobar
  6136. self.ui.position_label.setText("")
  6137. # self.ui.rel_position_label.setText("")
  6138. # first clear previous text in text editor (if any)
  6139. self.source_editor_tab.code_editor.clear()
  6140. self.source_editor_tab.code_editor.setReadOnly(False)
  6141. self.source_editor_tab.code_editor.completer_enable = False
  6142. self.source_editor_tab.buttonRun.hide()
  6143. # Switch plot_area to CNCJob tab
  6144. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6145. try:
  6146. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6147. except TypeError:
  6148. pass
  6149. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6150. try:
  6151. self.source_editor_tab.buttonSave.clicked.disconnect()
  6152. except TypeError:
  6153. pass
  6154. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6155. # then append the text from GCode to the text editor
  6156. if obj.kind == 'cncjob':
  6157. try:
  6158. file = obj.export_gcode(
  6159. preamble=self.defaults["cncjob_prepend"],
  6160. postamble=self.defaults["cncjob_append"],
  6161. to_file=True)
  6162. if file == 'fail':
  6163. return 'fail'
  6164. except AttributeError:
  6165. self.inform.emit('[WARNING_NOTCL] %s' %
  6166. _("There is no selected object for which to see it's source file code."))
  6167. return 'fail'
  6168. else:
  6169. try:
  6170. file = StringIO(obj.source_file)
  6171. except (AttributeError, TypeError):
  6172. self.inform.emit('[WARNING_NOTCL] %s' %
  6173. _("There is no selected object for which to see it's source file code."))
  6174. return 'fail'
  6175. self.source_editor_tab.t_frame.hide()
  6176. try:
  6177. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6178. # for line in file:
  6179. # QtWidgets.QApplication.processEvents()
  6180. # proc_line = str(line).strip('\n')
  6181. # self.source_editor_tab.code_editor.append(proc_line)
  6182. except Exception as e:
  6183. log.debug('App.on_view_source() -->%s' % str(e))
  6184. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6185. return
  6186. self.source_editor_tab.handleTextChanged()
  6187. self.source_editor_tab.t_frame.show()
  6188. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6189. self.proc_container.view.set_idle()
  6190. # self.ui.show()
  6191. def on_toggle_code_editor(self):
  6192. self.defaults.report_usage("on_toggle_code_editor()")
  6193. if self.toggle_codeeditor is False:
  6194. self.init_code_editor(name=_("Code Editor"))
  6195. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6196. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6197. self.text_editor_tab.buttonSave.clicked.disconnect()
  6198. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6199. else:
  6200. for idx in range(self.ui.plot_tab_area.count()):
  6201. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6202. self.ui.plot_tab_area.closeTab(idx)
  6203. break
  6204. self.toggle_codeeditor = False
  6205. def on_code_editor_close(self):
  6206. self.toggle_codeeditor = False
  6207. def goto_text_line(self):
  6208. """
  6209. Will scroll a text to the specified text line.
  6210. :return: None
  6211. """
  6212. dia_box = Dialog_box(title=_("Go to Line ..."),
  6213. label=_("Line:"),
  6214. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6215. initial_text='')
  6216. try:
  6217. line = int(dia_box.location) - 1
  6218. except (ValueError, TypeError):
  6219. line = 0
  6220. if dia_box.ok:
  6221. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6222. # at the top of the window
  6223. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6224. # get the document() of the TextEditor
  6225. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6226. # create a Text Cursor based on the searched line
  6227. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6228. # set cursor of the code editor with the cursor at the searcehd line
  6229. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6230. def on_filenewscript(self, silent=False):
  6231. """
  6232. Will create a new script file and open it in the Code Editor
  6233. :param silent: if True will not display status messages
  6234. :return: None
  6235. """
  6236. if silent is False:
  6237. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6238. # delete the absolute and relative position and messages in the infobar
  6239. self.ui.position_label.setText("")
  6240. # self.ui.rel_position_label.setText("")
  6241. self.app_obj.new_script_object()
  6242. # script_text = script_obj.source_file
  6243. #
  6244. # self.proc_container.view.set_busy(_("Loading..."))
  6245. # script_obj.script_editor_tab.t_frame.hide()
  6246. #
  6247. # script_obj.script_editor_tab.t_frame.show()
  6248. # self.proc_container.view.set_idle()
  6249. def on_fileopenscript(self, name=None, silent=False):
  6250. """
  6251. Will open a Tcl script file into the Code Editor
  6252. :param silent: if True will not display status messages
  6253. :param name: name of a Tcl script file to open
  6254. :return: None
  6255. """
  6256. self.defaults.report_usage("on_fileopenscript")
  6257. App.log.debug("on_fileopenscript()")
  6258. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6259. "All Files (*.*)"
  6260. if name:
  6261. filenames = [name]
  6262. else:
  6263. try:
  6264. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6265. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6266. except TypeError:
  6267. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6268. if len(filenames) == 0:
  6269. if silent is False:
  6270. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6271. else:
  6272. for filename in filenames:
  6273. if filename != '':
  6274. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6275. def on_fileopenscript_example(self, name=None, silent=False):
  6276. """
  6277. Will open a Tcl script file into the Code Editor
  6278. :param silent: if True will not display status messages
  6279. :param name: name of a Tcl script file to open
  6280. :return:
  6281. """
  6282. self.defaults.report_usage("on_fileopenscript_example")
  6283. log.debug("on_fileopenscript_example()")
  6284. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6285. "All Files (*.*)"
  6286. # test if the app was frozen and choose the path for the configuration file
  6287. if getattr(sys, "frozen", False) is True:
  6288. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6289. else:
  6290. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6291. if name:
  6292. filenames = [name]
  6293. else:
  6294. try:
  6295. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6296. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6297. except TypeError:
  6298. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6299. if len(filenames) == 0:
  6300. if silent is False:
  6301. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6302. else:
  6303. for filename in filenames:
  6304. if filename != '':
  6305. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6306. def on_filerunscript(self, name=None, silent=False):
  6307. """
  6308. File menu callback for loading and running a TCL script.
  6309. :param silent: if True will not display status messages
  6310. :param name: name of a Tcl script file to be run by FlatCAM
  6311. :return: None
  6312. """
  6313. self.defaults.report_usage("on_filerunscript")
  6314. App.log.debug("on_file_runscript()")
  6315. if name:
  6316. filename = name
  6317. if self.cmd_line_headless != 1:
  6318. self.splash.showMessage('%s: %ssec\n%s' %
  6319. (_("Canvas initialization started.\n"
  6320. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6321. _("Executing ScriptObject file.")
  6322. ),
  6323. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6324. color=QtGui.QColor("gray"))
  6325. else:
  6326. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6327. "All Files (*.*)"
  6328. try:
  6329. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6330. directory=self.get_last_folder(), filter=_filter_)
  6331. except TypeError:
  6332. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6333. # The Qt methods above will return a QString which can cause problems later.
  6334. # So far json.dump() will fail to serialize it.
  6335. filename = str(filename)
  6336. if filename == "":
  6337. if silent is False:
  6338. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6339. else:
  6340. if self.cmd_line_headless != 1:
  6341. if self.ui.shell_dock.isHidden():
  6342. self.ui.shell_dock.show()
  6343. try:
  6344. with open(filename, "r") as tcl_script:
  6345. cmd_line_shellfile_content = tcl_script.read()
  6346. if self.cmd_line_headless != 1:
  6347. self.shell.exec_command(cmd_line_shellfile_content)
  6348. else:
  6349. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6350. if silent is False:
  6351. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6352. except Exception as e:
  6353. log.debug("App.on_filerunscript() -> %s" % str(e))
  6354. sys.exit(2)
  6355. def on_file_saveproject(self, silent=False):
  6356. """
  6357. Callback for menu item File->Save Project. Saves the project to
  6358. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6359. if set to None. The project is saved by calling ``self.save_project()``.
  6360. :param silent: if True will not display status messages
  6361. :return: None
  6362. """
  6363. self.defaults.report_usage("on_file_saveproject")
  6364. if self.project_filename is None:
  6365. self.on_file_saveprojectas()
  6366. else:
  6367. self.worker_task.emit({'fcn': self.save_project,
  6368. 'params': [self.project_filename, silent]})
  6369. if self.defaults["global_open_style"] is False:
  6370. self.file_opened.emit("project", self.project_filename)
  6371. self.file_saved.emit("project", self.project_filename)
  6372. self.set_ui_title(name=self.project_filename)
  6373. self.should_we_save = False
  6374. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6375. """
  6376. Callback for menu item File->Save Project As... Opens a file
  6377. chooser and saves the project to the given file via
  6378. ``self.save_project()``.
  6379. :param make_copy if to be create a copy of the project; boolean
  6380. :param use_thread: if to be run in a separate thread; boolean
  6381. :param quit_action: if to be followed by quiting the application; boolean
  6382. :return: None
  6383. """
  6384. self.defaults.report_usage("on_file_saveprojectas")
  6385. self.date = str(datetime.today()).rpartition('.')[0]
  6386. self.date = ''.join(c for c in self.date if c not in ':-')
  6387. self.date = self.date.replace(' ', '_')
  6388. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6389. try:
  6390. filename, _f = FCFileSaveDialog.get_saved_filename(
  6391. caption=_("Save Project As ..."),
  6392. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6393. proj=_("Project")),
  6394. filter=filter_
  6395. )
  6396. except TypeError:
  6397. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6398. filename = str(filename)
  6399. if filename == '':
  6400. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6401. return
  6402. if use_thread is True:
  6403. self.worker_task.emit({'fcn': self.save_project,
  6404. 'params': [filename, quit_action]})
  6405. else:
  6406. self.save_project(filename, quit_action)
  6407. # self.save_project(filename)
  6408. if self.defaults["global_open_style"] is False:
  6409. self.file_opened.emit("project", filename)
  6410. self.file_saved.emit("project", filename)
  6411. if not make_copy:
  6412. self.project_filename = filename
  6413. self.set_ui_title(name=self.project_filename)
  6414. self.should_we_save = False
  6415. def on_file_save_objects_pdf(self, use_thread=True):
  6416. self.date = str(datetime.today()).rpartition('.')[0]
  6417. self.date = ''.join(c for c in self.date if c not in ':-')
  6418. self.date = self.date.replace(' ', '_')
  6419. try:
  6420. obj_selection = self.collection.get_selected()
  6421. if len(obj_selection) == 1:
  6422. obj_name = str(obj_selection[0].options['name'])
  6423. else:
  6424. obj_name = _("FlatCAM objects print")
  6425. except AttributeError as err:
  6426. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6427. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6428. return
  6429. if not obj_selection:
  6430. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6431. return
  6432. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6433. try:
  6434. filename, _f = FCFileSaveDialog.get_saved_filename(
  6435. caption=_("Save Object as PDF ..."),
  6436. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6437. obj_name=obj_name,
  6438. date=self.date),
  6439. filter=filter_
  6440. )
  6441. except TypeError:
  6442. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6443. filename = str(filename)
  6444. if filename == '':
  6445. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6446. return
  6447. if use_thread is True:
  6448. self.proc_container.new(_("Printing PDF ... Please wait."))
  6449. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6450. else:
  6451. self.save_pdf(filename, obj_selection)
  6452. # self.save_project(filename)
  6453. if self.defaults["global_open_style"] is False:
  6454. self.file_opened.emit("pdf", filename)
  6455. self.file_saved.emit("pdf", filename)
  6456. def save_pdf(self, file_name, obj_selection):
  6457. p_size = self.defaults['global_workspaceT']
  6458. orientation = self.defaults['global_workspace_orientation']
  6459. color = 'black'
  6460. transparency_level = 1.0
  6461. self.pagesize = {}
  6462. self.pagesize.update(
  6463. {
  6464. 'Bounds': None,
  6465. 'A0': (841 * mm, 1189 * mm),
  6466. 'A1': (594 * mm, 841 * mm),
  6467. 'A2': (420 * mm, 594 * mm),
  6468. 'A3': (297 * mm, 420 * mm),
  6469. 'A4': (210 * mm, 297 * mm),
  6470. 'A5': (148 * mm, 210 * mm),
  6471. 'A6': (105 * mm, 148 * mm),
  6472. 'A7': (74 * mm, 105 * mm),
  6473. 'A8': (52 * mm, 74 * mm),
  6474. 'A9': (37 * mm, 52 * mm),
  6475. 'A10': (26 * mm, 37 * mm),
  6476. 'B0': (1000 * mm, 1414 * mm),
  6477. 'B1': (707 * mm, 1000 * mm),
  6478. 'B2': (500 * mm, 707 * mm),
  6479. 'B3': (353 * mm, 500 * mm),
  6480. 'B4': (250 * mm, 353 * mm),
  6481. 'B5': (176 * mm, 250 * mm),
  6482. 'B6': (125 * mm, 176 * mm),
  6483. 'B7': (88 * mm, 125 * mm),
  6484. 'B8': (62 * mm, 88 * mm),
  6485. 'B9': (44 * mm, 62 * mm),
  6486. 'B10': (31 * mm, 44 * mm),
  6487. 'C0': (917 * mm, 1297 * mm),
  6488. 'C1': (648 * mm, 917 * mm),
  6489. 'C2': (458 * mm, 648 * mm),
  6490. 'C3': (324 * mm, 458 * mm),
  6491. 'C4': (229 * mm, 324 * mm),
  6492. 'C5': (162 * mm, 229 * mm),
  6493. 'C6': (114 * mm, 162 * mm),
  6494. 'C7': (81 * mm, 114 * mm),
  6495. 'C8': (57 * mm, 81 * mm),
  6496. 'C9': (40 * mm, 57 * mm),
  6497. 'C10': (28 * mm, 40 * mm),
  6498. # American paper sizes
  6499. 'LETTER': (8.5 * inch, 11 * inch),
  6500. 'LEGAL': (8.5 * inch, 14 * inch),
  6501. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6502. # From https://en.wikipedia.org/wiki/Paper_size
  6503. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6504. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6505. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6506. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6507. 'LEDGER': (17 * inch, 11 * inch),
  6508. }
  6509. )
  6510. exported_svg = []
  6511. for obj in obj_selection:
  6512. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6513. scale_factor_x=None, scale_factor_y=None,
  6514. skew_factor_x=None, skew_factor_y=None,
  6515. mirror=None)
  6516. if obj.kind.lower() == 'gerber':
  6517. # color = self.defaults["gerber_plot_fill"][:-2]
  6518. color = obj.fill_color[:-2]
  6519. elif obj.kind.lower() == 'excellon':
  6520. color = '#C40000'
  6521. elif obj.kind.lower() == 'geometry':
  6522. color = self.defaults["global_draw_color"]
  6523. # Change the attributes of the exported SVG
  6524. # We don't need stroke-width
  6525. # We set opacity to maximum
  6526. # We set the colour to WHITE
  6527. root = ET.fromstring(svg_obj)
  6528. for child in root:
  6529. child.set('fill', str(color))
  6530. child.set('opacity', str(transparency_level))
  6531. child.set('stroke', str(color))
  6532. exported_svg.append(ET.tostring(root))
  6533. xmin = Inf
  6534. ymin = Inf
  6535. xmax = -Inf
  6536. ymax = -Inf
  6537. for obj in obj_selection:
  6538. try:
  6539. gxmin, gymin, gxmax, gymax = obj.bounds()
  6540. xmin = min([xmin, gxmin])
  6541. ymin = min([ymin, gymin])
  6542. xmax = max([xmax, gxmax])
  6543. ymax = max([ymax, gymax])
  6544. except Exception as e:
  6545. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6546. # Determine bounding area for svg export
  6547. bounds = [xmin, ymin, xmax, ymax]
  6548. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6549. # This contain the measure units
  6550. uom = obj_selection[0].units.lower()
  6551. # Define a boundary around SVG of about 1.0mm (~39mils)
  6552. if uom in "mm":
  6553. boundary = 1.0
  6554. else:
  6555. boundary = 0.0393701
  6556. # Convert everything to strings for use in the xml doc
  6557. svgwidth = str(size[0] + (2 * boundary))
  6558. svgheight = str(size[1] + (2 * boundary))
  6559. minx = str(bounds[0] - boundary)
  6560. miny = str(bounds[1] + boundary + size[1])
  6561. # Add a SVG Header and footer to the svg output from shapely
  6562. # The transform flips the Y Axis so that everything renders
  6563. # properly within svg apps such as inkscape
  6564. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6565. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6566. svg_header += 'width="' + svgwidth + uom + '" '
  6567. svg_header += 'height="' + svgheight + uom + '" '
  6568. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6569. svg_header += '>'
  6570. svg_header += '<g transform="scale(1,-1)">'
  6571. svg_footer = '</g> </svg>'
  6572. svg_elem = str(svg_header)
  6573. for svg_item in exported_svg:
  6574. svg_elem += str(svg_item)
  6575. svg_elem += str(svg_footer)
  6576. # Parse the xml through a xml parser just to add line feeds
  6577. # and to make it look more pretty for the output
  6578. doc = parse_xml_string(svg_elem)
  6579. doc_final = doc.toprettyxml()
  6580. try:
  6581. if self.defaults['units'].upper() == 'IN':
  6582. unit = inch
  6583. else:
  6584. unit = mm
  6585. doc_final = StringIO(doc_final)
  6586. drawing = svg2rlg(doc_final)
  6587. if p_size == 'Bounds':
  6588. renderPDF.drawToFile(drawing, file_name)
  6589. else:
  6590. if orientation == 'p':
  6591. page_size = portrait(self.pagesize[p_size])
  6592. else:
  6593. page_size = landscape(self.pagesize[p_size])
  6594. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6595. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6596. renderPDF.draw(drawing, my_canvas, 0, 0)
  6597. my_canvas.save()
  6598. except Exception as e:
  6599. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6600. return 'fail'
  6601. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6602. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6603. """
  6604. Exports a Geometry Object to an SVG file.
  6605. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6606. :param filename: Path to the SVG file to save to.
  6607. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6608. :return:
  6609. """
  6610. self.defaults.report_usage("export_svg()")
  6611. if filename is None:
  6612. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6613. is not None else self.defaults["global_last_folder"]
  6614. self.log.debug("export_svg()")
  6615. try:
  6616. obj = self.collection.get_by_name(str(obj_name))
  6617. except Exception:
  6618. # TODO: The return behavior has not been established... should raise exception?
  6619. return "Could not retrieve object: %s" % obj_name
  6620. with self.proc_container.new(_("Exporting SVG")) as proc:
  6621. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6622. # Determine bounding area for svg export
  6623. bounds = obj.bounds()
  6624. size = obj.size()
  6625. # Convert everything to strings for use in the xml doc
  6626. svgwidth = str(size[0])
  6627. svgheight = str(size[1])
  6628. minx = str(bounds[0])
  6629. miny = str(bounds[1] - size[1])
  6630. uom = obj.units.lower()
  6631. # Add a SVG Header and footer to the svg output from shapely
  6632. # The transform flips the Y Axis so that everything renders
  6633. # properly within svg apps such as inkscape
  6634. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6635. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6636. svg_header += 'width="' + svgwidth + uom + '" '
  6637. svg_header += 'height="' + svgheight + uom + '" '
  6638. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6639. svg_header += '<g transform="scale(1,-1)">'
  6640. svg_footer = '</g> </svg>'
  6641. svg_elem = svg_header + exported_svg + svg_footer
  6642. # Parse the xml through a xml parser just to add line feeds
  6643. # and to make it look more pretty for the output
  6644. svgcode = parse_xml_string(svg_elem)
  6645. svgcode = svgcode.toprettyxml()
  6646. try:
  6647. with open(filename, 'w') as fp:
  6648. fp.write(svgcode)
  6649. except PermissionError:
  6650. self.inform.emit('[WARNING] %s' %
  6651. _("Permission denied, saving not possible.\n"
  6652. "Most likely another app is holding the file open and not accessible."))
  6653. return 'fail'
  6654. if self.defaults["global_open_style"] is False:
  6655. self.file_opened.emit("SVG", filename)
  6656. self.file_saved.emit("SVG", filename)
  6657. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6658. def save_source_file(self, obj_name, filename, use_thread=True):
  6659. """
  6660. Exports a FlatCAM Object to an Gerber/Excellon file.
  6661. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6662. :param filename: Path to the Gerber file to save to.
  6663. :param use_thread: if to be run in a separate thread
  6664. :return:
  6665. """
  6666. self.defaults.report_usage("save source file()")
  6667. if filename is None:
  6668. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6669. is not None else self.defaults["global_last_folder"]
  6670. self.log.debug("save source file()")
  6671. obj = self.collection.get_by_name(obj_name)
  6672. file_string = StringIO(obj.source_file)
  6673. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6674. if file_string.getvalue() == '':
  6675. self.inform.emit('[ERROR_NOTCL] %s' %
  6676. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6677. return 'fail'
  6678. try:
  6679. with open(filename, 'w') as file:
  6680. file.writelines('G04*\n')
  6681. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6682. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6683. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6684. file.writelines('G04 Created on : %s*\n' % time_string)
  6685. for line in file_string:
  6686. file.writelines(line)
  6687. except PermissionError:
  6688. self.inform.emit('[WARNING] %s' %
  6689. _("Permission denied, saving not possible.\n"
  6690. "Most likely another app is holding the file open and not accessible."))
  6691. return 'fail'
  6692. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6693. """
  6694. Exports a Excellon Object to an Excellon file.
  6695. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6696. :param filename: Path to the Excellon file to save to.
  6697. :param local_use:
  6698. :param use_thread: if to be run in a separate thread
  6699. :return:
  6700. """
  6701. self.defaults.report_usage("export_excellon()")
  6702. if filename is None:
  6703. if self.defaults["global_last_save_folder"]:
  6704. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6705. else:
  6706. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6707. self.log.debug("export_excellon()")
  6708. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6709. self.defaults["excellon_exp_decimals"]
  6710. )
  6711. if local_use is None:
  6712. try:
  6713. obj = self.collection.get_by_name(str(obj_name))
  6714. except Exception:
  6715. return "Could not retrieve object: %s" % obj_name
  6716. else:
  6717. obj = local_use
  6718. if not isinstance(obj, ExcellonObject):
  6719. self.inform.emit('[ERROR_NOTCL] %s' %
  6720. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6721. return
  6722. # updated units
  6723. eunits = self.defaults["excellon_exp_units"]
  6724. ewhole = self.defaults["excellon_exp_integer"]
  6725. efract = self.defaults["excellon_exp_decimals"]
  6726. ezeros = self.defaults["excellon_exp_zeros"]
  6727. eformat = self.defaults["excellon_exp_format"]
  6728. slot_type = self.defaults["excellon_exp_slot_type"]
  6729. fc_units = self.defaults['units'].upper()
  6730. if fc_units == 'MM':
  6731. factor = 1 if eunits == 'METRIC' else 0.03937
  6732. else:
  6733. factor = 25.4 if eunits == 'METRIC' else 1
  6734. def make_excellon():
  6735. try:
  6736. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6737. header = 'M48\n'
  6738. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6739. (str(self.version), str(self.version_date))
  6740. header += ';Filename: %s' % str(obj_name) + '\n'
  6741. header += ';Created on : %s' % time_str + '\n'
  6742. if eformat == 'dec':
  6743. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6744. header += eunits + '\n'
  6745. for tool in obj.tools:
  6746. if eunits == 'METRIC':
  6747. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6748. tool=str(tool),
  6749. dec=2)
  6750. else:
  6751. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6752. tool=str(tool),
  6753. dec=4)
  6754. else:
  6755. if ezeros == 'LZ':
  6756. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6757. form='ndec', e_zeros='LZ', factor=factor,
  6758. slot_type=slot_type)
  6759. header += '%s,%s\n' % (eunits, 'LZ')
  6760. header += format_exc
  6761. for tool in obj.tools:
  6762. if eunits == 'METRIC':
  6763. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6764. tool=str(tool),
  6765. dec=2)
  6766. else:
  6767. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6768. tool=str(tool),
  6769. dec=4)
  6770. else:
  6771. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6772. form='ndec', e_zeros='TZ', factor=factor,
  6773. slot_type=slot_type)
  6774. header += '%s,%s\n' % (eunits, 'TZ')
  6775. header += format_exc
  6776. for tool in obj.tools:
  6777. if eunits == 'METRIC':
  6778. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6779. tool=str(tool),
  6780. dec=2)
  6781. else:
  6782. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6783. tool=str(tool),
  6784. dec=4)
  6785. header += '%\n'
  6786. footer = 'M30\n'
  6787. exported_excellon = header
  6788. exported_excellon += excellon_code
  6789. exported_excellon += footer
  6790. if local_use is None:
  6791. try:
  6792. with open(filename, 'w') as fp:
  6793. fp.write(exported_excellon)
  6794. except PermissionError:
  6795. self.inform.emit('[WARNING] %s' %
  6796. _("Permission denied, saving not possible.\n"
  6797. "Most likely another app is holding the file open and not accessible."))
  6798. return 'fail'
  6799. if self.defaults["global_open_style"] is False:
  6800. self.file_opened.emit("Excellon", filename)
  6801. self.file_saved.emit("Excellon", filename)
  6802. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6803. else:
  6804. return exported_excellon
  6805. except Exception as e:
  6806. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6807. return 'fail'
  6808. if use_thread is True:
  6809. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6810. def job_thread_exc(app_obj):
  6811. ret = make_excellon()
  6812. if ret == 'fail':
  6813. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6814. return
  6815. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6816. else:
  6817. eret = make_excellon()
  6818. if eret == 'fail':
  6819. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6820. return 'fail'
  6821. if local_use is not None:
  6822. return eret
  6823. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6824. """
  6825. Exports a Gerber Object to an Gerber file.
  6826. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6827. :param filename: Path to the Gerber file to save to.
  6828. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6829. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6830. :param use_thread: if to be run in a separate thread
  6831. :return:
  6832. """
  6833. self.defaults.report_usage("export_gerber()")
  6834. if filename is None:
  6835. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6836. is not None else self.defaults["global_last_folder"]
  6837. self.log.debug("export_gerber()")
  6838. if local_use is None:
  6839. try:
  6840. obj = self.collection.get_by_name(str(obj_name))
  6841. except Exception:
  6842. return "Could not retrieve object: %s" % obj_name
  6843. else:
  6844. obj = local_use
  6845. # updated units
  6846. gunits = self.defaults["gerber_exp_units"]
  6847. gwhole = self.defaults["gerber_exp_integer"]
  6848. gfract = self.defaults["gerber_exp_decimals"]
  6849. gzeros = self.defaults["gerber_exp_zeros"]
  6850. fc_units = self.defaults['units'].upper()
  6851. if fc_units == 'MM':
  6852. factor = 1 if gunits == 'MM' else 0.03937
  6853. else:
  6854. factor = 25.4 if gunits == 'MM' else 1
  6855. def make_gerber():
  6856. try:
  6857. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6858. header = 'G04*\n'
  6859. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6860. (str(self.version), str(self.version_date))
  6861. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6862. header += 'G04 Created on : %s*' % time_str + '\n'
  6863. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6864. header += "%MO{units}*%\n".format(units=gunits)
  6865. for apid in obj.apertures:
  6866. if obj.apertures[apid]['type'] == 'C':
  6867. header += "%ADD{apid}{type},{size}*%\n".format(
  6868. apid=str(apid),
  6869. type='C',
  6870. size=(factor * obj.apertures[apid]['size'])
  6871. )
  6872. elif obj.apertures[apid]['type'] == 'R':
  6873. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6874. apid=str(apid),
  6875. type='R',
  6876. width=(factor * obj.apertures[apid]['width']),
  6877. height=(factor * obj.apertures[apid]['height'])
  6878. )
  6879. elif obj.apertures[apid]['type'] == 'O':
  6880. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6881. apid=str(apid),
  6882. type='O',
  6883. width=(factor * obj.apertures[apid]['width']),
  6884. height=(factor * obj.apertures[apid]['height'])
  6885. )
  6886. header += '\n'
  6887. # obsolete units but some software may need it
  6888. if gunits == 'IN':
  6889. header += 'G70*\n'
  6890. else:
  6891. header += 'G71*\n'
  6892. # Absolute Mode
  6893. header += 'G90*\n'
  6894. header += 'G01*\n'
  6895. # positive polarity
  6896. header += '%LPD*%\n'
  6897. footer = 'M02*\n'
  6898. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6899. exported_gerber = header
  6900. exported_gerber += gerber_code
  6901. exported_gerber += footer
  6902. if local_use is None:
  6903. try:
  6904. with open(filename, 'w') as fp:
  6905. fp.write(exported_gerber)
  6906. except PermissionError:
  6907. self.inform.emit('[WARNING] %s' %
  6908. _("Permission denied, saving not possible.\n"
  6909. "Most likely another app is holding the file open and not accessible."))
  6910. return 'fail'
  6911. if self.defaults["global_open_style"] is False:
  6912. self.file_opened.emit("Gerber", filename)
  6913. self.file_saved.emit("Gerber", filename)
  6914. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6915. else:
  6916. return exported_gerber
  6917. except Exception as e:
  6918. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6919. return 'fail'
  6920. if use_thread is True:
  6921. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6922. def job_thread_grb(app_obj):
  6923. ret = make_gerber()
  6924. if ret == 'fail':
  6925. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6926. return
  6927. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6928. else:
  6929. gret = make_gerber()
  6930. if gret == 'fail':
  6931. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6932. return 'fail'
  6933. if local_use is not None:
  6934. return gret
  6935. def export_dxf(self, obj_name, filename, use_thread=True):
  6936. """
  6937. Exports a Geometry Object to an DXF file.
  6938. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6939. :param filename: Path to the DXF file to save to.
  6940. :param use_thread: if to be run in a separate thread
  6941. :return:
  6942. """
  6943. self.defaults.report_usage("export_dxf()")
  6944. if filename is None:
  6945. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6946. is not None else self.defaults["global_last_folder"]
  6947. self.log.debug("export_dxf()")
  6948. try:
  6949. obj = self.collection.get_by_name(str(obj_name))
  6950. except Exception:
  6951. # TODO: The return behavior has not been established... should raise exception?
  6952. return "Could not retrieve object: %s" % obj_name
  6953. def make_dxf():
  6954. try:
  6955. dxf_code = obj.export_dxf()
  6956. dxf_code.saveas(filename)
  6957. if self.defaults["global_open_style"] is False:
  6958. self.file_opened.emit("DXF", filename)
  6959. self.file_saved.emit("DXF", filename)
  6960. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6961. except Exception:
  6962. return 'fail'
  6963. if use_thread is True:
  6964. with self.proc_container.new(_("Exporting DXF")) as proc:
  6965. def job_thread_exc(app_obj):
  6966. ret_dxf_val = make_dxf()
  6967. if ret_dxf_val == 'fail':
  6968. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6969. return
  6970. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6971. else:
  6972. ret = make_dxf()
  6973. if ret == 'fail':
  6974. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6975. return
  6976. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6977. """
  6978. Adds a new Geometry Object to the projects and populates
  6979. it with shapes extracted from the SVG file.
  6980. :param plot: If True then the resulting object will be plotted on canvas
  6981. :param filename: Path to the SVG file.
  6982. :param geo_type: Type of FlatCAM object that will be created from SVG
  6983. :param outname: The name given to the resulting FlatCAM object
  6984. :return:
  6985. """
  6986. self.defaults.report_usage("import_svg()")
  6987. log.debug("App.import_svg()")
  6988. obj_type = ""
  6989. if geo_type is None or geo_type == "geometry":
  6990. obj_type = "geometry"
  6991. elif geo_type == "gerber":
  6992. obj_type = "gerber"
  6993. else:
  6994. self.inform.emit('[ERROR_NOTCL] %s' %
  6995. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6996. return
  6997. units = self.defaults['units'].upper()
  6998. def obj_init(geo_obj, app_obj):
  6999. geo_obj.import_svg(filename, obj_type, units=units)
  7000. geo_obj.multigeo = False
  7001. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7002. with self.proc_container.new(_("Importing SVG")) as proc:
  7003. # Object name
  7004. name = outname or filename.split('/')[-1].split('\\')[-1]
  7005. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7006. if ret == 'fail':
  7007. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7008. return 'fail'
  7009. # Register recent file
  7010. self.file_opened.emit("svg", filename)
  7011. # AppGUI feedback
  7012. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7013. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7014. """
  7015. Adds a new Geometry Object to the projects and populates
  7016. it with shapes extracted from the DXF file.
  7017. :param filename: Path to the DXF file.
  7018. :param geo_type: Type of FlatCAM object that will be created from DXF
  7019. :param outname: Name for the imported Geometry
  7020. :param plot: If True then the resulting object will be plotted on canvas
  7021. :return:
  7022. """
  7023. self.defaults.report_usage("import_dxf()")
  7024. obj_type = ""
  7025. if geo_type is None or geo_type == "geometry":
  7026. obj_type = "geometry"
  7027. elif geo_type == "gerber":
  7028. obj_type = geo_type
  7029. else:
  7030. self.inform.emit('[ERROR_NOTCL] %s' %
  7031. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7032. return
  7033. units = self.defaults['units'].upper()
  7034. def obj_init(geo_obj, app_obj):
  7035. geo_obj.import_dxf(filename, obj_type, units=units)
  7036. geo_obj.multigeo = False
  7037. with self.proc_container.new(_("Importing DXF")):
  7038. # Object name
  7039. name = outname or filename.split('/')[-1].split('\\')[-1]
  7040. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7041. if ret == 'fail':
  7042. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7043. return 'fail'
  7044. # Register recent file
  7045. self.file_opened.emit("dxf", filename)
  7046. # AppGUI feedback
  7047. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7048. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7049. """
  7050. Opens a Gerber file, parses it and creates a new object for
  7051. it in the program. Thread-safe.
  7052. :param outname: Name of the resulting object. None causes the
  7053. name to be that of the file. Str.
  7054. :param filename: Gerber file filename
  7055. :type filename: str
  7056. :param plot: boolean, to plot or not the resulting object
  7057. :param from_tcl: True if run from Tcl Shell
  7058. :return: None
  7059. """
  7060. # How the object should be initialized
  7061. def obj_init(gerber_obj, app_obj):
  7062. assert isinstance(gerber_obj, GerberObject), \
  7063. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7064. # Opening the file happens here
  7065. try:
  7066. gerber_obj.parse_file(filename)
  7067. except IOError:
  7068. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7069. return "fail"
  7070. except ParseError as err:
  7071. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7072. app_obj.log.error(str(err))
  7073. return "fail"
  7074. except Exception as e:
  7075. log.debug("App.open_gerber() --> %s" % str(e))
  7076. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7077. msg += traceback.format_exc()
  7078. app_obj.inform.emit(msg)
  7079. return "fail"
  7080. if gerber_obj.is_empty():
  7081. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7082. _("Object is not Gerber file or empty. Aborting object creation."))
  7083. return "fail"
  7084. App.log.debug("open_gerber()")
  7085. with self.proc_container.new(_("Opening Gerber")):
  7086. # Object name
  7087. name = outname or filename.split('/')[-1].split('\\')[-1]
  7088. # # ## Object creation # ##
  7089. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7090. if ret_val == 'fail':
  7091. if from_tcl:
  7092. filename = self.defaults['global_tcl_path'] + '/' + name
  7093. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7094. if ret_val == 'fail':
  7095. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7096. return 'fail'
  7097. # Register recent file
  7098. self.file_opened.emit("gerber", filename)
  7099. # AppGUI feedback
  7100. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7101. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7102. """
  7103. Opens an Excellon file, parses it and creates a new object for
  7104. it in the program. Thread-safe.
  7105. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7106. :param filename: Excellon file filename
  7107. :type filename: str
  7108. :param plot: boolean, to plot or not the resulting object
  7109. :param from_tcl: True if run from Tcl Shell
  7110. :return: None
  7111. """
  7112. App.log.debug("open_excellon()")
  7113. # How the object should be initialized
  7114. def obj_init(excellon_obj, app_obj):
  7115. try:
  7116. ret = excellon_obj.parse_file(filename=filename)
  7117. if ret == "fail":
  7118. log.debug("Excellon parsing failed.")
  7119. self.inform.emit('[ERROR_NOTCL] %s' %
  7120. _("This is not Excellon file."))
  7121. return "fail"
  7122. except IOError:
  7123. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7124. (_("Cannot open file"), filename))
  7125. log.debug("Could not open Excellon object.")
  7126. return "fail"
  7127. except Exception:
  7128. msg = '[ERROR_NOTCL] %s' % \
  7129. _("An internal error has occurred. See shell.\n")
  7130. msg += traceback.format_exc()
  7131. app_obj.inform.emit(msg)
  7132. return "fail"
  7133. ret = excellon_obj.create_geometry()
  7134. if ret == 'fail':
  7135. log.debug("Could not create geometry for Excellon object.")
  7136. return "fail"
  7137. for tool in excellon_obj.tools:
  7138. if excellon_obj.tools[tool]['solid_geometry']:
  7139. return
  7140. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7141. return "fail"
  7142. with self.proc_container.new(_("Opening Excellon.")):
  7143. # Object name
  7144. name = outname or filename.split('/')[-1].split('\\')[-1]
  7145. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7146. if ret_val == 'fail':
  7147. if from_tcl:
  7148. filename = self.defaults['global_tcl_path'] + '/' + name
  7149. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7150. if ret_val == 'fail':
  7151. self.inform.emit('[ERROR_NOTCL] %s' %
  7152. _('Open Excellon file failed. Probable not an Excellon file.'))
  7153. return
  7154. # Register recent file
  7155. self.file_opened.emit("excellon", filename)
  7156. # AppGUI feedback
  7157. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7158. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7159. """
  7160. Opens a G-gcode file, parses it and creates a new object for
  7161. it in the program. Thread-safe.
  7162. :param filename: G-code file filename
  7163. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7164. :param force_parsing:
  7165. :param plot: If True plot the object on canvas
  7166. :param from_tcl: True if run from Tcl Shell
  7167. :return: None
  7168. """
  7169. App.log.debug("open_gcode()")
  7170. # How the object should be initialized
  7171. def obj_init(job_obj, app_obj_):
  7172. """
  7173. :param job_obj: the resulting object
  7174. :type app_obj_: App
  7175. """
  7176. assert isinstance(app_obj_, App), \
  7177. "Initializer expected App, got %s" % type(app_obj_)
  7178. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7179. try:
  7180. f = open(filename)
  7181. gcode = f.read()
  7182. f.close()
  7183. except IOError:
  7184. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7185. return "fail"
  7186. job_obj.gcode = gcode
  7187. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7188. if gcode_ret == "fail":
  7189. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7190. return "fail"
  7191. job_obj.create_geometry()
  7192. with self.proc_container.new(_("Opening G-Code.")):
  7193. # Object name
  7194. name = outname or filename.split('/')[-1].split('\\')[-1]
  7195. # New object creation and file processing
  7196. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7197. if ret_val == 'fail':
  7198. if from_tcl:
  7199. filename = self.defaults['global_tcl_path'] + '/' + name
  7200. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7201. if ret_val == 'fail':
  7202. self.inform.emit('[ERROR_NOTCL] %s' %
  7203. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7204. "Try to load it from File menu.\n "
  7205. "Attempting to create a FlatCAM CNCJob Object from "
  7206. "G-Code file failed during processing"))
  7207. return "fail"
  7208. # Register recent file
  7209. self.file_opened.emit("cncjob", filename)
  7210. # AppGUI feedback
  7211. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7212. def open_hpgl2(self, filename, outname=None):
  7213. """
  7214. Opens a HPGL2 file, parses it and creates a new object for
  7215. it in the program. Thread-safe.
  7216. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7217. :param filename: HPGL2 file filename
  7218. :return: None
  7219. """
  7220. filename = filename
  7221. # How the object should be initialized
  7222. def obj_init(geo_obj, app_obj):
  7223. assert isinstance(geo_obj, GeometryObject), \
  7224. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7225. # Opening the file happens here
  7226. obj = HPGL2(self)
  7227. try:
  7228. HPGL2.parse_file(obj, filename)
  7229. except IOError:
  7230. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7231. return "fail"
  7232. except ParseError as err:
  7233. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7234. app_obj.log.error(str(err))
  7235. return "fail"
  7236. except Exception as e:
  7237. log.debug("App.open_hpgl2() --> %s" % str(e))
  7238. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7239. msg += traceback.format_exc()
  7240. app_obj.inform.emit(msg)
  7241. return "fail"
  7242. geo_obj.multigeo = True
  7243. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7244. geo_obj.tools = deepcopy(obj.tools)
  7245. geo_obj.source_file = deepcopy(obj.source_file)
  7246. del obj
  7247. if not geo_obj.solid_geometry:
  7248. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7249. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7250. return "fail"
  7251. App.log.debug("open_hpgl2()")
  7252. with self.proc_container.new(_("Opening HPGL2")):
  7253. # Object name
  7254. name = outname or filename.split('/')[-1].split('\\')[-1]
  7255. # # ## Object creation # ##
  7256. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7257. if ret == 'fail':
  7258. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7259. return 'fail'
  7260. # Register recent file
  7261. self.file_opened.emit("geometry", filename)
  7262. # AppGUI feedback
  7263. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7264. def open_script(self, filename, outname=None, silent=False):
  7265. """
  7266. Opens a Script file, parses it and creates a new object for
  7267. it in the program. Thread-safe.
  7268. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7269. :param filename: Script file filename
  7270. :param silent: If True there will be no messages printed to StatusBar
  7271. :return: None
  7272. """
  7273. def obj_init(script_obj, app_obj):
  7274. assert isinstance(script_obj, ScriptObject), \
  7275. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7276. if silent is False:
  7277. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7278. try:
  7279. script_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_script() -> %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. App.log.debug("open_script()")
  7294. with self.proc_container.new(_("Opening TCL Script...")):
  7295. # Object name
  7296. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7297. # Object creation
  7298. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7299. if ret_val == 'fail':
  7300. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7301. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7302. if ret_val == 'fail':
  7303. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7304. return 'fail'
  7305. # Register recent file
  7306. self.file_opened.emit("script", filename)
  7307. # AppGUI feedback
  7308. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7309. def open_config_file(self, filename, run_from_arg=None):
  7310. """
  7311. Loads a config file from the specified file.
  7312. :param filename: Name of the file from which to load.
  7313. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7314. :return: None
  7315. """
  7316. App.log.debug("Opening config file: " + filename)
  7317. if run_from_arg:
  7318. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7319. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7320. _("Opening FlatCAM Config file.")),
  7321. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7322. color=QtGui.QColor("gray"))
  7323. # # add the tab if it was closed
  7324. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7325. # # first clear previous text in text editor (if any)
  7326. # self.ui.text_editor_tab.code_editor.clear()
  7327. #
  7328. # # Switch plot_area to CNCJob tab
  7329. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7330. # close the Code editor if already open
  7331. if self.toggle_codeeditor:
  7332. self.on_toggle_code_editor()
  7333. self.on_toggle_code_editor()
  7334. try:
  7335. if filename:
  7336. f = QtCore.QFile(filename)
  7337. if f.open(QtCore.QIODevice.ReadOnly):
  7338. stream = QtCore.QTextStream(f)
  7339. code_edited = stream.readAll()
  7340. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7341. f.close()
  7342. except IOError:
  7343. App.log.error("Failed to open config file: %s" % filename)
  7344. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7345. (_("Failed to open config file"), filename))
  7346. return
  7347. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7348. """
  7349. Loads a project from the specified file.
  7350. 1) Loads and parses file
  7351. 2) Registers the file as recently opened.
  7352. 3) Calls on_file_new()
  7353. 4) Updates options
  7354. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7355. 6) Calls plot_all() if plot=True
  7356. :param filename: Name of the file from which to load.
  7357. :param run_from_arg: True if run for arguments
  7358. :param plot: If True plot all objects in the project
  7359. :param cli: Run from command line
  7360. :param from_tcl: True if run from Tcl Sehll
  7361. :return: None
  7362. """
  7363. App.log.debug("Opening project: " + filename)
  7364. # block autosaving while a project is loaded
  7365. self.block_autosave = True
  7366. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7367. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7368. if cli is None:
  7369. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7370. if run_from_arg:
  7371. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7372. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7373. _("Opening FlatCAM Project file.")),
  7374. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7375. color=QtGui.QColor("gray"))
  7376. # Open and parse an uncompressed Project file
  7377. try:
  7378. f = open(filename, 'r')
  7379. except IOError:
  7380. if from_tcl:
  7381. name = filename.split('/')[-1].split('\\')[-1]
  7382. filename = self.defaults['global_tcl_path'] + '/' + name
  7383. try:
  7384. f = open(filename, 'r')
  7385. except IOError:
  7386. log.error("Failed to open project file: %s" % filename)
  7387. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7388. return
  7389. else:
  7390. log.error("Failed to open project file: %s" % filename)
  7391. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7392. return
  7393. try:
  7394. d = json.load(f, object_hook=dict2obj)
  7395. except Exception as e:
  7396. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7397. (filename, str(e)))
  7398. f.close()
  7399. # Open and parse a compressed Project file
  7400. try:
  7401. with lzma.open(filename) as f:
  7402. file_content = f.read().decode('utf-8')
  7403. d = json.loads(file_content, object_hook=dict2obj)
  7404. except Exception as e:
  7405. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7406. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7407. return
  7408. # Clear the current project
  7409. # # NOT THREAD SAFE # ##
  7410. if run_from_arg is True:
  7411. pass
  7412. elif cli is True:
  7413. self.delete_selection_shape()
  7414. else:
  7415. self.on_file_new()
  7416. # Project options
  7417. self.options.update(d['options'])
  7418. self.project_filename = filename
  7419. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7420. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7421. if cli is None:
  7422. self.set_screen_units(self.options["units"])
  7423. # Re create objects
  7424. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7425. for obj in d['objs']:
  7426. try:
  7427. def obj_init(obj_inst, app_inst):
  7428. obj_inst.from_dict(obj)
  7429. App.log.debug("Recreating from opened project an %s object: %s" %
  7430. (obj['kind'].capitalize(), obj['options']['name']))
  7431. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7432. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7433. if cli is None:
  7434. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7435. obj['kind'].upper(),
  7436. obj['options']['name']
  7437. )
  7438. )
  7439. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7440. except Exception as e:
  7441. print('App.open_project() --> ' + str(e))
  7442. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7443. self.should_we_save = False
  7444. self.file_opened.emit("project", filename)
  7445. # restore autosaving after a project was loaded
  7446. self.block_autosave = False
  7447. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7448. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7449. if cli is None:
  7450. self.set_ui_title(name=self.project_filename)
  7451. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7452. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7453. """
  7454. Re-generates all plots from all objects.
  7455. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7456. :param muted: if True don't print messages
  7457. :param use_thread: if True will use threading for plotting the objects
  7458. :return: None
  7459. """
  7460. self.log.debug("Plot_all()")
  7461. if muted is not True:
  7462. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7463. for plot_obj in self.collection.get_list():
  7464. def worker_task(obj):
  7465. with self.proc_container.new("Plotting"):
  7466. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7467. if fit_view is True:
  7468. self.app_obj.object_plotted.emit(obj)
  7469. if use_thread is True:
  7470. # Send to worker
  7471. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7472. else:
  7473. worker_task(plot_obj)
  7474. def register_folder(self, filename):
  7475. """
  7476. Register the last folder used by the app to open something
  7477. :param filename: the last folder is extracted from the filename
  7478. :return: None
  7479. """
  7480. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7481. def register_save_folder(self, filename):
  7482. """
  7483. Register the last folder used by the app to save something
  7484. :param filename: the last folder is extracted from the filename
  7485. :return: None
  7486. """
  7487. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7488. # def set_progress_bar(self, percentage, text=""):
  7489. # """
  7490. # Set a progress bar to a value (percentage)
  7491. #
  7492. # :param percentage: Value set to the progressbar
  7493. # :param text: Not used
  7494. # :return: None
  7495. # """
  7496. # self.ui.progress_bar.setValue(int(percentage))
  7497. def setup_recent_items(self):
  7498. """
  7499. Setup a dictionary with the recent files accessed, organized by type
  7500. :return:
  7501. """
  7502. icons = {
  7503. "gerber": self.resource_location + "/flatcam_icon16.png",
  7504. "excellon": self.resource_location + "/drill16.png",
  7505. 'geometry': self.resource_location + "/geometry16.png",
  7506. "cncjob": self.resource_location + "/cnc16.png",
  7507. "script": self.resource_location + "/script_new24.png",
  7508. "document": self.resource_location + "/notes16_1.png",
  7509. "project": self.resource_location + "/project16.png",
  7510. "svg": self.resource_location + "/geometry16.png",
  7511. "dxf": self.resource_location + "/dxf16.png",
  7512. "pdf": self.resource_location + "/pdf32.png",
  7513. "image": self.resource_location + "/image16.png"
  7514. }
  7515. try:
  7516. image_opener = self.image_tool.import_image
  7517. except AttributeError:
  7518. image_opener = None
  7519. openers = {
  7520. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7521. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7522. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7523. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7524. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7525. "document": None,
  7526. 'project': self.open_project,
  7527. 'svg': self.import_svg,
  7528. 'dxf': self.import_dxf,
  7529. 'image': image_opener,
  7530. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7531. }
  7532. # Open recent file for files
  7533. try:
  7534. f = open(self.data_path + '/recent.json')
  7535. except IOError:
  7536. App.log.error("Failed to load recent item list.")
  7537. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7538. return
  7539. try:
  7540. self.recent = json.load(f)
  7541. except json.errors.JSONDecodeError:
  7542. App.log.error("Failed to parse recent item list.")
  7543. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7544. f.close()
  7545. return
  7546. f.close()
  7547. # Open recent file for projects
  7548. try:
  7549. fp = open(self.data_path + '/recent_projects.json')
  7550. except IOError:
  7551. App.log.error("Failed to load recent project item list.")
  7552. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7553. return
  7554. try:
  7555. self.recent_projects = json.load(fp)
  7556. except json.errors.JSONDecodeError:
  7557. App.log.error("Failed to parse recent project item list.")
  7558. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7559. fp.close()
  7560. return
  7561. fp.close()
  7562. # Closure needed to create callbacks in a loop.
  7563. # Otherwise late binding occurs.
  7564. def make_callback(func, fname):
  7565. def opener():
  7566. func(fname)
  7567. return opener
  7568. def reset_recent_files():
  7569. # Reset menu
  7570. self.ui.recent.clear()
  7571. self.recent = []
  7572. try:
  7573. ff = open(self.data_path + '/recent.json', 'w')
  7574. except IOError:
  7575. App.log.error("Failed to open recent items file for writing.")
  7576. return
  7577. json.dump(self.recent, ff)
  7578. def reset_recent_projects():
  7579. # Reset menu
  7580. self.ui.recent_projects.clear()
  7581. self.recent_projects = []
  7582. try:
  7583. frp = open(self.data_path + '/recent_projects.json', 'w')
  7584. except IOError:
  7585. App.log.error("Failed to open recent projects items file for writing.")
  7586. return
  7587. json.dump(self.recent, frp)
  7588. # Reset menu
  7589. self.ui.recent.clear()
  7590. self.ui.recent_projects.clear()
  7591. # Create menu items for projects
  7592. for recent in self.recent_projects:
  7593. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7594. if recent['kind'] == 'project':
  7595. try:
  7596. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7597. # Attach callback
  7598. o = make_callback(openers[recent["kind"]], recent['filename'])
  7599. action.triggered.connect(o)
  7600. self.ui.recent_projects.addAction(action)
  7601. except KeyError:
  7602. App.log.error("Unsupported file type: %s" % recent["kind"])
  7603. # Last action in Recent Files menu is one that Clear the content
  7604. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7605. (_("Clear Recent projects")), self)
  7606. clear_action_proj.triggered.connect(reset_recent_projects)
  7607. self.ui.recent_projects.addSeparator()
  7608. self.ui.recent_projects.addAction(clear_action_proj)
  7609. # Create menu items for files
  7610. for recent in self.recent:
  7611. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7612. if recent['kind'] != 'project':
  7613. try:
  7614. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7615. # Attach callback
  7616. o = make_callback(openers[recent["kind"]], recent['filename'])
  7617. action.triggered.connect(o)
  7618. self.ui.recent.addAction(action)
  7619. except KeyError:
  7620. App.log.error("Unsupported file type: %s" % recent["kind"])
  7621. # Last action in Recent Files menu is one that Clear the content
  7622. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7623. (_("Clear Recent files")), self)
  7624. clear_action.triggered.connect(reset_recent_files)
  7625. self.ui.recent.addSeparator()
  7626. self.ui.recent.addAction(clear_action)
  7627. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7628. # self.ui.menufilerecent.set_submenu(recent_menu)
  7629. # recent_menu.show_all()
  7630. # self.ui.recent.show()
  7631. self.log.debug("Recent items list has been populated.")
  7632. def setup_component_editor(self):
  7633. """
  7634. Default text for the Selected tab when is not taken by the Object UI.
  7635. :return:
  7636. """
  7637. # label = QtWidgets.QLabel("Choose an item from Project")
  7638. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7639. sel_title = QtWidgets.QTextEdit(
  7640. _('<b>Shortcut Key List</b>'))
  7641. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7642. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7643. f_settings = QSettings("Open Source", "FlatCAM")
  7644. if f_settings.contains("notebook_font_size"):
  7645. fsize = f_settings.value('notebook_font_size', type=int)
  7646. else:
  7647. fsize = 12
  7648. tsize = fsize + int(fsize / 2)
  7649. # selected_text = (_('''
  7650. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7651. # </p>
  7652. #
  7653. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7654. # The normal flow when working in FlatCAM is the following:</span></p>
  7655. #
  7656. # <ol>
  7657. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7658. # file into
  7659. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7660. # even dragging and dropping the files on the AppGUI.<br />
  7661. # <br />
  7662. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7663. # drop of the
  7664. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7665. # &nbsp;</li>
  7666. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7667. # and then
  7668. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7669. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7670. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7671. # <br />
  7672. # If the selection of the object is done on the canvas by single click instead, and the
  7673. # <strong>SELECTED TAB</strong>
  7674. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7675. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7676. # it even if it was out of focus.<br />
  7677. # <br />
  7678. # You can change the parameters in this screen and the flow direction is like this:<br />
  7679. # <br />
  7680. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7681. # <strong> Geometry Object
  7682. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7683. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7684. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7685. # </ol>
  7686. #
  7687. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7688. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7689. # <strong>F3</strong>.</span></p>
  7690. #
  7691. # ''').format(fsize=fsize, tsize=tsize))
  7692. selected_text = '''
  7693. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7694. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7695. {s1}</span></p>
  7696. <ol>
  7697. <li><span style="font-size:{fsize}px">{s2}<br />
  7698. <br />
  7699. {s3}</span><br />
  7700. &nbsp;</li>
  7701. <li><span style="font-size:{fsize}px">{s4}<br />
  7702. &nbsp;</li>
  7703. <br />
  7704. <li><span style="font-size:{fsize}px">{s5}<br />
  7705. &nbsp;</li>
  7706. <br />
  7707. <li><span style="font-size:{fsize}px">{s6}<br />
  7708. <br />
  7709. {s7}</span></li>
  7710. </ol>
  7711. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7712. '''.format(
  7713. title=_("Selected Tab - Choose an Item from Project Tab"),
  7714. subtitle=_("Details"),
  7715. s1=_("The normal flow when working in FlatCAM is the following:"),
  7716. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7717. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7718. "files on the AppGUI."),
  7719. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7720. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7721. "actions offered within the app."),
  7722. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7723. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7724. "SELECTED TAB will be updated with the object properties according to its kind: "
  7725. "Gerber, Excellon, Geometry or CNCJob object."),
  7726. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7727. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7728. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7729. "the SELECTED TAB and populate it even if it was out of focus."),
  7730. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7731. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7732. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7733. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7734. "(again, done in SELECTED TAB) --> Save GCode."),
  7735. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7736. "or through its own key shortcut: <b>F3</b>."),
  7737. tsize=tsize,
  7738. fsize=fsize
  7739. )
  7740. sel_title.setText(selected_text)
  7741. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7742. self.ui.selected_scroll_area.setWidget(sel_title)
  7743. def setup_obj_classes(self):
  7744. """
  7745. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7746. class.
  7747. :return: None
  7748. """
  7749. FlatCAMObj.app = self
  7750. ObjectCollection.app = self
  7751. Gerber.app = self
  7752. Excellon.app = self
  7753. Geometry.app = self
  7754. CNCjob.app = self
  7755. FCProcess.app = self
  7756. FCProcessContainer.app = self
  7757. OptionsGroupUI.app = self
  7758. def version_check(self):
  7759. """
  7760. Checks for the latest version of the program. Alerts the
  7761. user if theirs is outdated. This method is meant to be run
  7762. in a separate thread.
  7763. :return: None
  7764. """
  7765. self.log.debug("version_check()")
  7766. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7767. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7768. App.version_url,
  7769. str(self.defaults['global_serial']),
  7770. str(self.version),
  7771. str(self.os),
  7772. urllib.parse.urlencode(self.defaults["global_stats"])
  7773. )
  7774. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7775. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7776. # urllib.parse.urlencode(self.defaults["global_stats"])
  7777. else:
  7778. # no_stats dict; just so it won't break things on website
  7779. no_ststs_dict = {}
  7780. no_ststs_dict["global_ststs"] = {}
  7781. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7782. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7783. App.log.debug("Checking for updates @ %s" % full_url)
  7784. # ## Get the data
  7785. try:
  7786. f = urllib.request.urlopen(full_url)
  7787. except Exception:
  7788. # App.log.warning("Failed checking for latest version. Could not connect.")
  7789. self.log.warning("Failed checking for latest version. Could not connect.")
  7790. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7791. return
  7792. try:
  7793. data = json.load(f)
  7794. except Exception as e:
  7795. App.log.error("Could not parse information about latest version.")
  7796. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7797. App.log.debug("json.load(): %s" % str(e))
  7798. f.close()
  7799. return
  7800. f.close()
  7801. # ## Latest version?
  7802. if self.version >= data["version"]:
  7803. App.log.debug("FlatCAM is up to date!")
  7804. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7805. return
  7806. App.log.debug("Newer version available.")
  7807. self.message.emit(
  7808. _("Newer Version Available"),
  7809. '%s<br><br>><b>%s</b><br>%s' % (
  7810. _("There is a newer version of FlatCAM available for download:"),
  7811. str(data["name"]),
  7812. str(data["message"])
  7813. ),
  7814. _("info")
  7815. )
  7816. def on_plotcanvas_setup(self, container=None):
  7817. """
  7818. This is doing the setup for the plot area (canvas).
  7819. :param container: QT Widget where to install the canvas
  7820. :return: None
  7821. """
  7822. if container:
  7823. plot_container = container
  7824. else:
  7825. plot_container = self.ui.right_layout
  7826. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7827. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7828. self.is_legacy = True
  7829. self.defaults["global_graphic_engine"] = "2D"
  7830. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7831. else:
  7832. try:
  7833. self.plotcanvas = PlotCanvas(plot_container, self)
  7834. except Exception as er:
  7835. msg_txt = traceback.format_exc()
  7836. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7837. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7838. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7839. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7840. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7841. msg += msg_txt
  7842. self.inform.emit(msg)
  7843. return 'fail'
  7844. # So it can receive key presses
  7845. self.plotcanvas.native.setFocus()
  7846. if self.is_legacy is False:
  7847. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7848. # Set the mouse button for panning
  7849. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7850. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7851. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7852. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7853. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7854. # Keys over plot enabled
  7855. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7856. if self.defaults['global_cursor_type'] == 'small':
  7857. self.app_cursor = self.plotcanvas.new_cursor()
  7858. else:
  7859. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7860. if self.ui.grid_snap_btn.isChecked():
  7861. self.app_cursor.enabled = True
  7862. else:
  7863. self.app_cursor.enabled = False
  7864. if self.is_legacy is False:
  7865. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7866. else:
  7867. # will use the default Matplotlib axes
  7868. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7869. def on_zoom_fit(self):
  7870. """
  7871. Callback for zoom-fit request. This can be either from the corresponding
  7872. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7873. with axes limits from the geometry bounds of all objects.
  7874. :return: None
  7875. """
  7876. if self.is_legacy is False:
  7877. self.plotcanvas.fit_view()
  7878. else:
  7879. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7880. width = xmax - xmin
  7881. height = ymax - ymin
  7882. xmin -= 0.05 * width
  7883. xmax += 0.05 * width
  7884. ymin -= 0.05 * height
  7885. ymax += 0.05 * height
  7886. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7887. def on_zoom_in(self):
  7888. """
  7889. Callback for zoom-in request.
  7890. :return:
  7891. """
  7892. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7893. def on_zoom_out(self):
  7894. """
  7895. Callback for zoom-out request.
  7896. :return:
  7897. """
  7898. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7899. def disable_all_plots(self):
  7900. self.defaults.report_usage("disable_all_plots()")
  7901. self.disable_plots(self.collection.get_list())
  7902. self.inform.emit('[success] %s' %
  7903. _("All plots disabled."))
  7904. def disable_other_plots(self):
  7905. self.defaults.report_usage("disable_other_plots()")
  7906. self.disable_plots(self.collection.get_non_selected())
  7907. self.inform.emit('[success] %s' %
  7908. _("All non selected plots disabled."))
  7909. def enable_all_plots(self):
  7910. self.defaults.report_usage("enable_all_plots()")
  7911. self.enable_plots(self.collection.get_list())
  7912. self.inform.emit('[success] %s' %
  7913. _("All plots enabled."))
  7914. def on_enable_sel_plots(self):
  7915. log.debug("App.on_enable_sel_plot()")
  7916. object_list = self.collection.get_selected()
  7917. self.enable_plots(objects=object_list)
  7918. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7919. def on_disable_sel_plots(self):
  7920. log.debug("App.on_disable_sel_plot()")
  7921. # self.inform.emit(_("Disabling plots ..."))
  7922. object_list = self.collection.get_selected()
  7923. self.disable_plots(objects=object_list)
  7924. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7925. def enable_plots(self, objects):
  7926. """
  7927. Enable plots
  7928. :param objects: list of Objects to be enabled
  7929. :return:
  7930. """
  7931. log.debug("Enabling plots ...")
  7932. # self.inform.emit(_("Working ..."))
  7933. for obj in objects:
  7934. if obj.options['plot'] is False:
  7935. obj.options.set_change_callback(lambda x: None)
  7936. obj.options['plot'] = True
  7937. try:
  7938. # only the Gerber obj has on_plot_cb_click() method
  7939. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7940. # disable this cb while disconnected,
  7941. # in case the operation takes time the user is not allowed to change it
  7942. obj.ui.plot_cb.setDisabled(True)
  7943. except AttributeError:
  7944. pass
  7945. obj.set_form_item("plot")
  7946. try:
  7947. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7948. obj.ui.plot_cb.setDisabled(False)
  7949. except AttributeError:
  7950. pass
  7951. obj.options.set_change_callback(obj.on_options_change)
  7952. def worker_task(objs):
  7953. with self.proc_container.new(_("Enabling plots ...")):
  7954. for plot_obj in objs:
  7955. # obj.options['plot'] = True
  7956. if isinstance(plot_obj, CNCJobObject):
  7957. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7958. else:
  7959. plot_obj.plot(visible=True)
  7960. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7961. def disable_plots(self, objects):
  7962. """
  7963. Disables plots
  7964. :param objects: list of Objects to be disabled
  7965. :return:
  7966. """
  7967. # if no objects selected then do nothing
  7968. if not self.collection.get_selected():
  7969. return
  7970. log.debug("Disabling plots ...")
  7971. # self.inform.emit(_("Working ..."))
  7972. for obj in objects:
  7973. if obj.options['plot'] is True:
  7974. obj.options.set_change_callback(lambda x: None)
  7975. obj.options['plot'] = False
  7976. try:
  7977. # only the Gerber obj has on_plot_cb_click() method
  7978. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7979. obj.ui.plot_cb.setDisabled(True)
  7980. except AttributeError:
  7981. pass
  7982. obj.set_form_item("plot")
  7983. try:
  7984. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7985. obj.ui.plot_cb.setDisabled(False)
  7986. except AttributeError:
  7987. pass
  7988. obj.options.set_change_callback(obj.on_options_change)
  7989. try:
  7990. self.delete_selection_shape()
  7991. except Exception as e:
  7992. log.debug("App.disable_plots() --> %s" % str(e))
  7993. def worker_task(objs):
  7994. with self.proc_container.new(_("Disabling plots ...")):
  7995. for plot_obj in objs:
  7996. # obj.options['plot'] = True
  7997. if isinstance(plot_obj, CNCJobObject):
  7998. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7999. else:
  8000. plot_obj.plot(visible=False)
  8001. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8002. def toggle_plots(self, objects):
  8003. """
  8004. Toggle plots visibility
  8005. :param objects: list of Objects for which to be toggled the visibility
  8006. :return: None
  8007. """
  8008. # if no objects selected then do nothing
  8009. if not self.collection.get_selected():
  8010. return
  8011. log.debug("Toggling plots ...")
  8012. self.inform.emit(_("Working ..."))
  8013. for obj in objects:
  8014. if obj.options['plot'] is False:
  8015. obj.options['plot'] = True
  8016. else:
  8017. obj.options['plot'] = False
  8018. self.app_obj.plots_updated.emit()
  8019. def clear_plots(self):
  8020. """
  8021. Clear the plots
  8022. :return: None
  8023. """
  8024. objects = self.collection.get_list()
  8025. for obj in objects:
  8026. obj.clear(obj == objects[-1])
  8027. # Clear pool to free memory
  8028. self.clear_pool()
  8029. def on_set_color_action_triggered(self):
  8030. """
  8031. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8032. :return:
  8033. """
  8034. new_color = self.defaults['gerber_plot_fill']
  8035. clicked_action = self.sender()
  8036. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8037. act_name = clicked_action.text()
  8038. sel_obj_list = self.collection.get_selected()
  8039. if not sel_obj_list:
  8040. return
  8041. # a default value, I just chose this one
  8042. alpha_level = 'BF'
  8043. for sel_obj in sel_obj_list:
  8044. if sel_obj.kind == 'excellon':
  8045. alpha_level = str(hex(
  8046. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8047. elif sel_obj.kind == 'gerber':
  8048. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8049. elif sel_obj.kind == 'geometry':
  8050. alpha_level = 'FF'
  8051. else:
  8052. log.debug(
  8053. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8054. continue
  8055. sel_obj.alpha_level = alpha_level
  8056. if act_name == _('Red'):
  8057. new_color = '#FF0000' + alpha_level
  8058. if act_name == _('Blue'):
  8059. new_color = '#0000FF' + alpha_level
  8060. if act_name == _('Yellow'):
  8061. new_color = '#FFDF00' + alpha_level
  8062. if act_name == _('Green'):
  8063. new_color = '#00FF00' + alpha_level
  8064. if act_name == _('Purple'):
  8065. new_color = '#FF00FF' + alpha_level
  8066. if act_name == _('Brown'):
  8067. new_color = '#A52A2A' + alpha_level
  8068. if act_name == _('White'):
  8069. new_color = '#FFFFFF' + alpha_level
  8070. if act_name == _('Black'):
  8071. new_color = '#000000' + alpha_level
  8072. if act_name == _('Custom'):
  8073. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8074. c_dialog = QtWidgets.QColorDialog()
  8075. plot_fill_color = c_dialog.getColor(initial=new_color)
  8076. if plot_fill_color.isValid() is False:
  8077. return
  8078. new_color = str(plot_fill_color.name()) + alpha_level
  8079. if act_name == _("Default"):
  8080. for sel_obj in sel_obj_list:
  8081. if sel_obj.kind == 'excellon':
  8082. new_color = self.defaults['excellon_plot_fill']
  8083. new_line_color = self.defaults['excellon_plot_line']
  8084. elif sel_obj.kind == 'gerber':
  8085. new_color = self.defaults['gerber_plot_fill']
  8086. new_line_color = self.defaults['gerber_plot_line']
  8087. elif sel_obj.kind == 'geometry':
  8088. new_color = self.defaults['geometry_plot_line']
  8089. new_line_color = self.defaults['geometry_plot_line']
  8090. else:
  8091. log.debug(
  8092. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8093. continue
  8094. sel_obj.fill_color = new_color
  8095. sel_obj.outline_color = new_line_color
  8096. sel_obj.shapes.redraw(
  8097. update_colors=(new_color, new_line_color)
  8098. )
  8099. return
  8100. if act_name == _("Opacity"):
  8101. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8102. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8103. if ok_button:
  8104. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8105. for sel_obj in sel_obj_list:
  8106. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8107. sel_obj.shapes.redraw(
  8108. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8109. )
  8110. return
  8111. new_line_color = color_variant(new_color[:7], 0.7)
  8112. if act_name == _("White"):
  8113. new_line_color = color_variant("#dedede", 0.7)
  8114. for sel_obj in sel_obj_list:
  8115. sel_obj.fill_color = new_color
  8116. sel_obj.outline_color = new_line_color
  8117. sel_obj.shapes.redraw(
  8118. update_colors=(new_color, new_line_color)
  8119. )
  8120. def generate_cnc_job(self, objects):
  8121. """
  8122. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8123. :param objects: Selected objects in the Project Tab
  8124. :return:
  8125. """
  8126. self.defaults.report_usage("generate_cnc_job()")
  8127. # for obj in objects:
  8128. # obj.generatecncjob()
  8129. for obj in objects:
  8130. obj.on_generatecnc_button_click()
  8131. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8132. """
  8133. Saves the current project to the specified file.
  8134. :param filename: Name of the file in which to save.
  8135. :type filename: str
  8136. :param quit_action: if the project saving will be followed by an app quit; boolean
  8137. :param silent: if True will not display status messages
  8138. :param from_tcl True is run from Tcl Shell
  8139. :return: None
  8140. """
  8141. self.log.debug("save_project()")
  8142. self.save_in_progress = True
  8143. with self.proc_container.new(_("Saving FlatCAM Project")):
  8144. # Capture the latest changes
  8145. # Current object
  8146. try:
  8147. current_object = self.collection.get_active()
  8148. if current_object:
  8149. current_object.read_form()
  8150. except Exception as e:
  8151. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8152. pass
  8153. # Serialize the whole project
  8154. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8155. "options": self.options,
  8156. "version": self.version}
  8157. if self.defaults["global_save_compressed"] is True:
  8158. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8159. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8160. # # Write
  8161. f.write(g)
  8162. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8163. else:
  8164. # Open file
  8165. try:
  8166. f = open(filename, 'w')
  8167. except IOError:
  8168. App.log.error("Failed to open file for saving: %s", filename)
  8169. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8170. return
  8171. # Write
  8172. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8173. f.close()
  8174. # verification of the saved project
  8175. # Open and parse
  8176. try:
  8177. saved_f = open(filename, 'r')
  8178. except IOError:
  8179. if silent is False:
  8180. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8181. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8182. return
  8183. try:
  8184. saved_d = json.load(saved_f, object_hook=dict2obj)
  8185. except Exception:
  8186. if silent is False:
  8187. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8188. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8189. f.close()
  8190. return
  8191. saved_f.close()
  8192. if silent is False:
  8193. if 'version' in saved_d:
  8194. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8195. else:
  8196. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8197. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8198. tb_settings = QSettings("Open Source", "FlatCAM")
  8199. lock_state = self.ui.lock_action.isChecked()
  8200. tb_settings.setValue('toolbar_lock', lock_state)
  8201. # This will write the setting to the platform specific storage.
  8202. del tb_settings
  8203. # if quit:
  8204. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8205. # t.start()
  8206. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8207. def start_delayed_quit(self, delay, filename, should_quit=None):
  8208. """
  8209. :param delay: period of checking if project file size is more than zero; in seconds
  8210. :param filename: the name of the project file to be checked periodically for size more than zero
  8211. :param should_quit: if the task finished will be followed by an app quit; boolean
  8212. :return:
  8213. """
  8214. to_quit = should_quit
  8215. self.save_timer = QtCore.QTimer()
  8216. self.save_timer.setInterval(delay)
  8217. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8218. self.save_timer.start()
  8219. def check_project_file_size(self, filename, should_quit=None):
  8220. """
  8221. :param filename: the name of the project file to be checked periodically for size more than zero
  8222. :param should_quit: will quit the app if True; boolean
  8223. :return:
  8224. """
  8225. try:
  8226. if os.stat(filename).st_size > 0:
  8227. self.save_in_progress = False
  8228. self.save_timer.stop()
  8229. if should_quit:
  8230. self.app_quit.emit()
  8231. except Exception:
  8232. traceback.print_exc()
  8233. def save_project_auto(self):
  8234. """
  8235. Called periodically to save the project.
  8236. 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
  8237. # progress.
  8238. :return:
  8239. """
  8240. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8241. self.on_file_saveproject()
  8242. def save_project_auto_update(self):
  8243. """
  8244. Update the auto save time interval value.
  8245. :return:
  8246. """
  8247. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8248. try:
  8249. if self.autosave_timer.isActive():
  8250. self.autosave_timer.stop()
  8251. except Exception:
  8252. pass
  8253. if self.defaults['global_autosave'] is True:
  8254. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8255. self.autosave_timer.start()
  8256. def on_options_app2project(self):
  8257. """
  8258. Callback for Options->Transfer Options->App=>Project. Copies options
  8259. from application defaults to project defaults.
  8260. :return: None
  8261. """
  8262. self.defaults.report_usage("on_options_app2project")
  8263. self.preferencesUiManager.defaults_read_form()
  8264. self.options.update(self.defaults)
  8265. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8266. """
  8267. Shows a message on the FlatCAM Shell
  8268. :param msg: Message to display.
  8269. :param show: Opens the shell.
  8270. :param error: Shows the message as an error.
  8271. :param warning: Shows the message as an warning.
  8272. :param success: Shows the message as an success.
  8273. :param selected: Indicate that something was selected on canvas
  8274. :return: None
  8275. """
  8276. if show:
  8277. self.ui.shell_dock.show()
  8278. try:
  8279. if error:
  8280. self.shell.append_error(msg + "\n")
  8281. elif warning:
  8282. self.shell.append_warning(msg + "\n")
  8283. elif success:
  8284. self.shell.append_success(msg + "\n")
  8285. elif selected:
  8286. self.shell.append_selected(msg + "\n")
  8287. else:
  8288. self.shell.append_output(msg + "\n")
  8289. except AttributeError:
  8290. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8291. class ArgsThread(QtCore.QObject):
  8292. open_signal = pyqtSignal(list)
  8293. start = pyqtSignal()
  8294. stop = pyqtSignal()
  8295. if sys.platform == 'win32':
  8296. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8297. else:
  8298. address = ('/tmp/testipc', 'AF_UNIX')
  8299. def __init__(self):
  8300. super(ArgsThread, self).__init__()
  8301. self.listener = None
  8302. self.thread_exit = False
  8303. self.start.connect(self.run)
  8304. self.stop.connect(self.close_listener)
  8305. def my_loop(self, address):
  8306. try:
  8307. self.listener = Listener(*address)
  8308. while self.thread_exit is False:
  8309. conn = self.listener.accept()
  8310. self.serve(conn)
  8311. except socket.error:
  8312. try:
  8313. conn = Client(*address)
  8314. conn.send(sys.argv)
  8315. conn.send('close')
  8316. # close the current instance only if there are args
  8317. if len(sys.argv) > 1:
  8318. try:
  8319. self.listener.close()
  8320. except Exception:
  8321. pass
  8322. sys.exit()
  8323. except ConnectionRefusedError:
  8324. if sys.platform == 'win32':
  8325. pass
  8326. else:
  8327. os.system('rm /tmp/testipc')
  8328. self.listener = Listener(*address)
  8329. while True:
  8330. conn = self.listener.accept()
  8331. self.serve(conn)
  8332. def serve(self, conn):
  8333. while self.thread_exit is False:
  8334. msg = conn.recv()
  8335. if msg == 'close':
  8336. break
  8337. self.open_signal.emit(msg)
  8338. conn.close()
  8339. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8340. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8341. @pyqtSlot()
  8342. def run(self):
  8343. self.my_loop(self.address)
  8344. @pyqtSlot()
  8345. def close_listener(self):
  8346. self.thread_exit = True
  8347. self.listener.close()
  8348. # end of file